2016-07-29 45 views
2

存在以及计算此的替代方法?LINQ通过并正确计数加入群组

IList<DtoProfile> profileList = Session().QueryOver<DtoProfile>() 
IList<Headword> methodList = Session().QueryOver<Headword>() 
var hList = profileList.Select(x => x.HeadwordList).SelectMany(x => x).ToList(); 

profileList包含一个HeadwordList。现在hList包含像

Headword1词目:ID = 1,文本=文本1(从配置文件1)
Headword2:ID = 2,文本=文本2(从配置文件1)
Headword1:ID = 1,文本文本1 =(从 资料2)

methodList时包含

Headword1:ID = 1,文本=文本1
Headword2:我d = 2,文本=文本2
Headword2:ID = 3,文字=文本3

我想使一个字典等

键:文本1,值:2
键:文本2,价值:1
键:文本3,值:0

var joined = (from headword in methodList 
    join profile in hList on headword equals profile 
    group headword by headword.Text 
    into groupedProfile 
    select groupedProfile).ToDictionary(x => x.Key, x => x.Count()); 

它不工作!我只是

键:文本1,值:2
键:文本2,值:1
在我的字典。 现在我提高到与左连接:

var joined = (from headword in methodList 
    join profile in hList on headword equals profile into ps 
    from profile in ps.DefaultIfEmpty() 
    group headword by headword.Text 
    into groupedProfile 
    select groupedProfile).ToDictionary(x => x.Key, x => x.Count(y => y != null)); 

但Y => Y = null未正常工作! 我得到:

键:文本1,值:2
键:文本2,值:1
键:文本3,值:1(错了,应该是0)

+0

这些'QueryOver'方法实际返回列表?如果将它保留为“IQueryable”,您可以更好地优化它。 –

回答

2

我我真的不知道,如果我明白你的问题,但也许...

var joined = methodList 
    .ToDictionary(item => item.Text, item => hList.Count(h => h.Text == item.Text)) 
+0

是的,这正是我需要的。谢谢! – Xeddon