LINQ中有两个可用的投影运算符。1)Select 2)SelectMany
Select运算符始终返回IEnumerable集合,该集合包含基于转换函数的元素。它类似于产生平面结果集的SQL的Select子句。
现在,让我们了解使用以下Student类的Select查询运算符。
public class Student{ public int StudentID { get; set; } public string StudentName { get; set; } public int Age { get; set; } }
LINQ查询语法必须以Select 或 GroupBy子句结尾。下面的示例演示了Select 运算符,该运算符返回StudentName的字符串集合。
IList<Student> studentList = new List<Student>() { new Student() { StudentID = 1, StudentName = "John" }, new Student() { StudentID = 2, StudentName = "Moin" }, new Student() { StudentID = 3, StudentName = "Bill" }, new Student() { StudentID = 4, StudentName = "Ram" }, new Student() { StudentID = 5, StudentName = "Ron" } }; var selectResult = from s in studentList select s.StudentName;
选择运算符可用于根据我们的要求制定结果。它可用于返回自定义类或匿名类型的集合,其中包括根据我们的需要的属性。
下面的select子句示例返回一个包含Name和Age属性的匿名类型的集合。
IList<Student> studentList = new List<Student>() { new Student() { StudentID = 1, StudentName = "John", Age = 13 } , new Student() { StudentID = 2, StudentName = "Moin", Age = 21 } , new Student() { StudentID = 3, StudentName = "Bill", Age = 18 } , new Student() { StudentID = 4, StudentName = "Ram" , Age = 20 } , new Student() { StudentID = 5, StudentName = "Ron" , Age = 15 } }; // 返回具有Name和Age属性的匿名对象的集合 var selectResult = from s in studentList select new { Name = "Mr. " + s.StudentName, Age = s.Age }; // 迭代selectResult foreach (var item in selectResult) Console.WriteLine("Student Name: {0}, Age: {1}", item.Name, item.Age);
Dim selectResult = From s In studentList Select New With {.Name = s.StudentName, .Age = s.Age}
输出:
Student Name: Mr. John, Age: 13 Student Name: Mr. Moin, Age: 21 Student Name: Mr. Bill, Age: 18 Student Name: Mr. Ram, Age: 20 Student Name: Mr. Ron, Age: 15
Select运算符在方法语法中是可选的。但是,您可以使用它来塑造数据。在以下示例中,Select扩展方法返回具有Name和Age属性的匿名对象的集合:
示例:C#在方法语法中的Select
IList<Student> studentList = new List<Student>() { new Student() { StudentID = 1, StudentName = "John", Age = 18 } , new Student() { StudentID = 2, StudentName = "Moin", Age = 21 } , new Student() { StudentID = 3, StudentName = "Bill", Age = 18 } , new Student() { StudentID = 4, StudentName = "Ram" , Age = 20 } , new Student() { StudentID = 5, StudentName = "Ron" , Age = 21 } }; var selectResult = studentList.Select(s => new { Name = s.StudentName , Age = s.Age });
在上面的示例中,selectResult将包含具有Name和Age属性的匿名对象,如下面的调试视图所示。
Dim selectResult = studentList.Select(Function(s) New With {.Name = s.StudentName, .Age = s.Age})
SelectMany 运算符投射基于转换函数的值序列,然后将它们扁平化为一个序列。