Linq分组操作之GroupBy,GroupJoin扩展方法源码分析
一. GroupBy
解释: 根据指定的键选择器函数对序列中的元素进行分组,并且从每个组及其键中创建结果值。
查询表达式:
var list = new List<object>() { 20, 30, 24 };查询表达式:
var query = from n in list
group n by n
into grp
select new
{
MyKey = grp.Key,
MyValue = grp.Count()
};
//如下: 会以Key 为分组,与sql一样
var wordList = new List<word>()
{
new word { Key="dragon", length=, str=""},
new word { Key="dragon", length=, str=""},
new word { Key="joc", length=, str=""} };
var keyCount = wordList.GroupBy(i=>i.Key).ToArray();
二. GroupJoin
解释:基于键相等对两个序列的元素进行关联并对结果进行分组。使用默认的相等比较器对键进行比较。
也就是关联后的分组
var query2 = from n in wordList
join m in word2List
on n.Key equals m.Key
into grp
select new
{
Key = n.Key,
Value = grp.Count()
};