LINQ查询
1.查询语法与方法语法
查询语法:
var queryResults =
from n in names
where n.StartsWith("S")
select n;
方法语法:
var queryResults = names.Where(n=>n.StartsWith("S"));
2.查询排序
默认升序,添加descending关键字则为降序
var queryResults =
from n in names
where n.StartsWith("S")
orderby n descending
select n;
3.聚合运算
var queryResults= from n in numbers
where n>1000
select n;
var maxNum=queryResult.Max();
4.投影:在查询中创建新类型
List<Customer> customers=new List<Customer>{new Customer{ID="A",City="Beijing",Country="China",Region="Asia",Sales=9}}
var queryResults=
from c in customers
where c.Region="Asia"
select new {c.City,c.Country,c.Sales};
5.Any()和All()方法
bool anyUSA=customers.Any(c=>c.Country=="USA");
bool allAsia=customers.All(c=>c.Region=="Asia");
6.多级排序
var queryResults= 或 var queryResults=customers.OrderBy(c=>c.Region)
from c in customers .ThenBy(c=>c.Country)
orderby c.Region,c.Country,c.City .ThenBy(c=>c.City)
select new {c.ID,c.Region,c.Country,c.City}; .Select(c=>new {c.ID,c.Region,c.Country,c.City})
7.组合查询
var queryResults=
from c in customers
group c by c.Region into cg
select new {TotalSales=cg.Sum(c=>c.Sales),Region=cg.Key};
8.Take()和Skip()方法
queryResults.Take(n):取前n个数据 queryResults.Skip(n):跳过前n个数据
9.Frist()和FristOrDefalt()方法
Frist()如果没有满足条件的会报错,而FristOrDefalt不会
10.集运算Intersect(),Except(),Union()方法
11.多表查询join...on...
var queryResults=
from c in customers
join o in orders on c.Id equals o.Id