Select运算符为属于投影运算符类别的每个源SelectMany运算符产生一个结果值。它用于将序列的每个元素投影到IEnumerable并将生成的序列展平为一个序列。
class Demo{ public string Name { get; set; } public List<string> Contents { get; set; } public static List<Demo>GetAllContents(){ List<Demo> listContents = new List<Demo>{ new Demo{ Name = "Cap", Contents = new List<string> { "Nike", "Adidas" } }, new Demo{ Name = "Shoes", Contents = new List<string> { "Nike", "Puma", "Adidas" } }, }; return listContents; } } class Program{ static void Main(){ IEnumerable<List<string>> result = Demo.GetAllContents().Select(s => s.Contents); foreach (List<string> stringList in result){ foreach (string str in stringList){ Console.WriteLine(str); } } Console.WriteLine("---Select Many---") IEnumerable<string> resultSelectMany = Demo.GetAllContents().SelectMany(s => s.Contents); foreach (string str in resultSelectMany){ Console.WriteLine(str); } Console.ReadKey(); } }
输出结果
Nike Adidas Nike Puma Adidas ---Select Many--- Nike Adidas Nike Puma Adidas