通过对象和集合初始值设定项,初始化对象时无需为对象显式调用构造函数。 初始值设定项通常用在将源数据投影到新数据类型的查询表达式中。 假定一个类名为 Customer,具有公共 Name 和 Phone 属性,可以按下列代码中所示使用对象初始值设定项:
1 2 3 4
Customer cust = new Customer { Name = "Mike", Phone = "555-1212" }; var newLargeOrderCustomers = from o in IncomingOrders where o.OrderSize > 5 selectnew Customer { Name = o.Name, Phone = o.Phone };
述代码也可以使用 LINQ 的方法语法编写:
1
var newLargeOrderCustomers = IncomingOrders.Where(x => x.OrderSize > 5).Select(y => new Customer { Name = y.Name, Phone = y.Phone });
var evenNumQuery = from num in numbers where (num % 2) == 0 select num;
int evenNumCount = evenNumQuery.Count();
要强制立即执行任何查询并缓存其结果,可调用 ToList 或 ToArray 方法。
1 2 3 4 5 6 7 8 9 10 11 12
List<int> numQuery2 = (from num in numbers where (num % 2) == 0 select num).ToList();
// or like this: // numQuery3 is still an int[]
var numQuery3 = (from num in numbers where (num % 2) == 0 select num).ToArray();
基本 LINQ 查询操作
获取数据源
使用 from 子句引入数据源:
1 2 3
//queryAllCustomers is an IEnumerable<Customer> var queryAllCustomers = from cust in customers select cust;
可通过 let 子句引入其他范围变量。
1 2 3 4 5 6 7 8 9
var earlyBirdQuery = from sentence in strings let words = sentence.Split(' ') from word in words let w = word.ToLower() where w[0] == 'a' || w[0] == 'e' || w[0] == 'i' || w[0] == 'o' || w[0] == 'u' select word;
筛选
筛选器使查询仅返回表达式为 true 的元素。 将通过使用 where 子句生成结果。
1 2 3
var queryLondonCustomers = from cust in customers where cust.City == "London" select cust;
中间件排序
orderby 子句根据要排序类型的默认比较器,对返回序列中的元素排序。
1 2 3 4 5
var queryLondonCustomers3 = from cust in customers where cust.City == "London" orderby cust.Name ascending select cust;
要对结果进行从 Z 到 A 的逆序排序,请使用 orderby…descending 子句。
分组
group 子句用于对根据指定的键所获得的结果进行分组。
使用 group 子句结束查询时,结果将以列表的形式列出。 列表中的每个元素都是具有 Key 成员的对象,列表中的元素根据该键被分组。 在循环访问生成组序列的查询时,必须使用嵌套 foreach 循环。 外层循环循环访问每个组,内层循环循环访问每个组的成员。
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// queryCustomersByCity is an IEnumerable<IGrouping<string, Customer>> var queryCustomersByCity = from cust in customers group cust by cust.City;
// customerGroup is an IGrouping<string, Customer> foreach (var customerGroup in queryCustomersByCity) { Console.WriteLine(customerGroup.Key); foreach (Customer customer in customerGroup) { Console.WriteLine(" {0}", customer.Name); } }
如果必须引用某个组操作的结果,可使用 into 关键字创建能被进一步查询的标识符。 下列查询仅返回包含两个以上客户的组:
1 2 3 4 5 6 7
// custQuery is an IEnumerable<IGrouping<string, Customer>> var custQuery = from cust in customers group cust by cust.City into custGroup where custGroup.Count() > 2 orderby custGroup.Key select custGroup;
联接
在 LINQ 中,join 子句始终作用于对象集合,而非直接作用于数据库表。
1 2 3 4
var innerJoinQuery = from cust in customers join dist in distributors on cust.City equals dist.City selectnew { CustomerName = cust.Name, DistributorName = dist.Name };
classStudent { publicstring First { get; set; } publicstring Last {get; set;} publicint ID { get; set; } publicstring Street { get; set; } publicstring City { get; set; } public List<int> Scores; }
classTeacher { publicstring First { get; set; } publicstring Last { get; set; } publicint ID { get; set; } publicstring City { get; set; } } classDataTransformations { staticvoidMain() { // Create the first data source. List<Student> students = new List<Student>() { new Student { First="Svetlana", Last="Omelchenko", ID=111, Street="123 Main Street", City="Seattle", Scores= new List<int> { 97, 92, 81, 60 } }, new Student { First="Claire", Last="O’Donnell", ID=112, Street="124 Main Street", City="Redmond", Scores= new List<int> { 75, 84, 91, 39 } }, new Student { First="Sven", Last="Mortensen", ID=113, Street="125 Main Street", City="Lake City", Scores= new List<int> { 88, 94, 65, 91 } }, };
// Create the second data source. List<Teacher> teachers = new List<Teacher>() { new Teacher { First="Ann", Last="Beebe", ID=945, City="Seattle" }, new Teacher { First="Alex", Last="Robinson", ID=956, City="Redmond" }, new Teacher { First="Michiyo", Last="Sato", ID=972, City="Tacoma" } };
// Create the query. var peopleInSeattle = (from student in students where student.City == "Seattle" select student.Last) .Concat(from teacher in teachers where teacher.City == "Seattle" select teacher.Last);
Console.WriteLine("The following students and teachers live in Seattle:"); // Execute the query. foreach (var person in peopleInSeattle) { Console.WriteLine(person); }
Console.WriteLine("Press any key to exit."); Console.ReadKey(); } } /* Output: The following students and teachers live in Seattle: Omelchenko Beebe */
选择每个源元素的子集
有两种主要方法来选择源序列中每个元素的子集:
1,若要仅选择源元素的一个成员,请使用点操作。
1 2
var query = from cust in Customers select cust.City;
2,要创建包含多个源元素属性的元素,可以使用带有命名对象或匿名类型的对象初始值设定项。
1 2
var query = from cust in Customer selectnew {Name = cust.Name, City = cust.City};
将内存中对象转换为 XML
LINQ 查询可以方便地在内存中数据结构、SQL 数据库、ADO.NET 数据集和 XML 流或文档之间转换数据。
staticvoidMain() { // Create the data source by using a collection initializer. // The Student class was defined previously in this topic. List<Student> students = new List<Student>() { new Student {First="Svetlana", Last="Omelchenko", ID=111, Scores = new List<int>{97, 92, 81, 60}}, new Student {First="Claire", Last="O’Donnell", ID=112, Scores = new List<int>{75, 84, 91, 39}}, new Student {First="Sven", Last="Mortensen", ID=113, Scores = new List<int>{88, 94, 65, 91}}, };
// Create the query. var studentsToXML = new XElement("Root", from student in students let scores = string.Join(",", student.Scores) selectnewXElement("student", new XElement("First", student.First), newXElement("Last", student.Last), newXElement("Scores", scores) ) // end "student" ); // end "Root"
// Execute the query. Console.WriteLine(studentsToXML);
// Keep the console open in debug mode. Console.WriteLine("Press any key to exit."); Console.ReadKey(); }