集合初始化器用来初始化一个集合,和对象初始化器有点类似,都是用一对{}来初始化。
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Linq; 6 7 namespace LinqDemo 8 { 9 class Program10 {11 static void Main(string[] args)12 {13 14 IList numberIds = new List () { 1,2,3,4,5,6,7,8,9};15 16 foreach (int i in numberIds)17 {18 Console.WriteLine(i.ToString());19 }20 21 Console.ReadKey();22 }23 24 25 }26 27 28 }
IList<int> numberIds = new List<int>() {1,2,3,4,5,6,7,8,9},()是可以省略的 IList<int> numberIds = new List<int>{1,2,3,4,5,6,7,8,9};
运行结果: