2016-07-29 44 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