C# Linq的分组功能

Linq在集合操作上很方便,很多语法都借鉴自sql,但linq的分组却与sql有一定的区别,故整理发布如下。 
1.  Linq分组
分组后以Key属性访问分组键值。
每一组为一个IEnumberAble或IQeuryAble的集合,可以继续枚举。.
Sample:

string[] World = { "Hello","World"};
string[] Brother = { "Hello","Brother"};
var result = from wld in World
from bth in Brother
group new { wld, bth } by new { wld, bth }.bth;
OR
var result = from wld in World
from bth in Brother
group new { wld, bth } by bth;

foreach (var obj in result)
{
foreach (var ct in obj)
{
Response.Write(ct.wld + ct.bth);
}
}

说明:在linq里面,group by 和groupby是两个不同的概念,前者标识分组,后者标识排序。分组时如不特意制定select,则将分组后的结果作为结果集。

2.   Linq排序后,分组再排序

public class Student
{
public string Name = "";
public string Sex = "";
public int Age;
}
Student[] stAry =
{
new Student{ Name ="Jon1",Sex="female",Age =21},
new Student{ Name ="Jon2",Sex="male",Age =22},
new Student{ Name ="Jon3",Sex="male",Age =33},
new Student{ Name ="Jon4s",Sex="female",Age =44},
new Student{ Name ="Jon5",Sex="female",Age =25},
new Student{ Name ="Jon6",Sex="female",Age =26}
};
var c = from st in stAry
orderby st.Age
group st by st.Sex into temp
orderby temp.Key ascending
select temp;

概要说明:
Linq查询后产生的结果集和sql类似,如果涉及到多个查询则会产生一个多“列”的集合用以“select”,如果用到linq的分组功能,则分组后的结果将作为一个“集合”,而这个集合可以在他所在的查询中作为一个源被查询,也可以当做一个元素被直接“select”。如下例所示。注意:Into在linq里面也用以分组,产生的结果用来查询,当然,不用这个结果也不会错。

3.   join分组:

int[] Ary1 = { 1, 23, 45, 67, 8, 4, 4 };
int[] Ary2 = { 23, 1, 1,5, 67, 4 };

var c = from A1 in Ary1
join A2 in Ary2 on A1 equals A2 into VAL2
select VAL2;

左外连接:

var c = from A1 in Ary1
join A2 in Ary2 on A1 equals A2 into VAL2
from a2 in VAL2. DefaultIfEmpty(int.MinValue)
select new {A1,a2,VAL2};

注:DefaultIfEmpty(int.MinValue)表示集合为空的时候,用指定的默认值关联前面的集合。如果不指定,则由于集合为空,A1找不到关联的对象将不产生相应的行。

4.   linq嵌套查询
  查询某个数据集中不全为null或“”的列

var c = from DataColumn dc in ds.Tables[0].Columns
where ( from dr in dt.AsEnumerable()
where !dr.IsNull(dc)
select dr
).Any()
select dc;