LINQ语句查询
linq查询表达式是linq中非常重要的一部分内容,它可以从一个或多个给定的数据源中检索数据,并指定检索结果的数据类型和表现形式。linq查询表达式由一个或多个linq查询子句按照一定的规则组成。linq查询八大语句表达式包括from子句、where子句、select子句、orderby子句、group子句、into子句、join子句、let子句。分为简单查询、复杂查询、聚合查询、分组查询。from... 子句:制定查询操作的数据源和范围变量
例如:
int[] values = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
var value = from v in values
where v < 6
select v;
Response.Write("查询结果:<br>");
foreach (var v in value)
{
Response.Write(v.ToString() + "<br>");
}
select子句:指定查询结果的类型和表现形式
例如:
int[] values = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
var value = from v in values
where v < 4
select v;
Response.Write("查询结果:<br>");
foreach (var v in value)
{
Response.Write(v.ToString() + "<br>");
}
where子句:筛选元素的逻辑条件,一般由逻辑运算符组成
例如:
int[] values = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
var value = from v in values
where v < 9 && v > 6
select v;
Response.Write("查询结果:<br>");
foreach (var v in value)
{
Response.Write(v.ToString() + "<br>");
}
group..by子句:对查询进行分组
例如:
protected void Page_Load(object sender, EventArgs e)
{
int[] values = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
var value = from v in values
group v by v % 2 == 0; ;
//输出查询结果
foreach (var i in value)
{
foreach (int j in i)
{
Response.Write(j + "<br>");
}
}
}
order...by子句:对查询结果进行排序,可以为升序或降序。
例如:
protected void Page_Load(object sender, EventArgs e)
{
int[] values = { 5, 8, 3, 4, 1, 6, 7, 2, 9, 0 };
var value = from v in values
where v < 3 || v > 6
orderby v descending
select v;
//输出查询结果
foreach (var i in value)
{
Response.Write(i + "<br>");
}
}
into子句:提供一个临时标示符,从当对join、group或select子句的结果
例如:
protected void Page_Load(object sender, EventArgs e)
{
int[] values = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
var value = from v in values
group v by v % 2 == 0 into g
where g.Max() > 8 //分组后 查找组中大于8的组
select g;
//输出查询结果
foreach (var i in value)
{
foreach (int j in i)
{
Response.Write(j + "<br>");
}
}
}
join子句:连接多个查询操作的数据源
例如:
private void InnerJoinQuery()
2 {
3
4 List<UserBaseInfo> users = new List<UserBaseInfo>();
5 List<RoleInfo> roles = new List<RoleInfo>();
6
7
8 for (int i = 1; i < 10; i++)
9 {
10 users.Add(new UserBaseInfo(i, "users0" + i.ToString(), "user0" + i.ToString() + "@web.com", i * 2));
11 roles.Add(new RoleInfo(i, "RoleName0" + i.ToString()));
12 }
13
14 //查询ID值小于9,且角色包含roles中的用户
15 var result = from u in users
16 join r in roles on u.RoleId equals r.ID
17
18 where u.ID < 9
19 select u;
20
21 foreach (var u in result)
22 {
23
24 Response.Write(u.UserName + "</br>");
25
26 }
27 }
let子句:引入用于存储查询表达式中的自表达式结果的范围变量
例如:
private void LetQuery()
2 {
3
4 List<UserBaseInfo> users = new List<UserBaseInfo>();
5
6 for(int i=1;i<10;i++)
7 {
8 users.Add(new UserBaseInfo(i,"users0"+i.ToString(),"user0"+i.ToString()+"@web.com"));
9 }
10
11 var result = from u in users
12 let number= Int32.Parse(u.UserName.Substring(u.UserName.Length - 2))
13 group u by number % 2 == 0 into g
14
15 where g.Count() < 5
16
17 select g;
18
19 foreach (var v in result)
20 {
21 foreach (UserBaseInfo u in v)
22 {
23 Response.Write(u.UserName + "</br>");
24 }
25 }
26 }