以上是LINQ的一些查询方法
-
using System; using System.Collections.Generic; using System.Linq; namespace TestLinq { class Program { static void Main(string[] args) { QueryOperations(); //调用 } public static void QueryOperations() { //1,Data Source //注意:想要用LINQ语句,必须实现IEnumerble接口,数组已经实现此接口 int[] numbers = new int[] { 0, 1, 2, 3, 4, 5, 6, 7 }; //2,Query creation var numQuery = from num in numbers where num % 2 == 1 && num % 3 == 1 orderby num ascending select num; //注意:此处并未执行LINQ语句,当被调用时才执行 //int numCount = numQuery.Count(); //强制执行LINQ语句,这样会提高执行的效率 //numQuery.ToList(); //numQuery.ToArray(); //3,Query execution foreach (var num in numQuery) //此处才执行LINQ语句 { Console.Write(num + " "); } Console.WriteLine(); List<Customer> customer = new List<Customer>(); customer.Add(new Customer() { Name = "ruanxiongfeng", City = "wuxi" }); customer.Add(new Customer() { Name = "zhanggang", City = "wuxi" }); customer.Add(new Customer() { Name = "wusuwen", City = "shanghai" }); List<Employee> employees = new List<Employee>(); employees.Add(new Employee() { Name = "ruanxiongfeng", ID = 101 }); employees.Add(new Employee() { Name = "wanglei", ID = 102 }); var queryCustomer = from c in customer group c by c.City; foreach (var cg in queryCustomer) { Console.WriteLine(cg.Key); foreach (var c in cg) { Console.WriteLine("{0}", c.Name); } } var queryEmployee = from c in customer join e in employees on c.Name equals e.Name select new { PersionName = c.Name, PersionID = e.ID, PersionCity = c.City }; foreach (var p in queryEmployee) { Console.WriteLine("{0} {1} {2}", p.PersionName, p.PersionID, p.PersionCity); } Console.ReadLine(); } } class Customer { public string Name { get; set; } public string City { get; set; } } class Employee { public string Name { get; set; } public int ID { get; set; } } }
- 以上是LINQ的一些用法