LINQ离开了group by并正确计数

时间:2016-07-29 20:57:27

标签: c# 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,Text = Text1(来自Profile 1)
  Headword2:ID = 2,Text = Text2(来自Profile 1)
  Headword1:ID = 1,Text = Text1(来自   简介2)

methodList包含

  

Headword1:ID = 1,Text = Text1
  Headword2:ID = 2,Text = Text2
  Headword2:ID = 3,Text = Text3

我想制作像

这样的词典
  

键:Text1,值:2
  键:Text2,值:1
  键:Text3,值: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());

它不起作用!我刚刚

  

键:Text1,值:2
  键:Text2,值: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 =&gt; y!= null无法正常工作! 我明白了:

  

键:Text1,值:2
   键:Text2,值:1
  键:Text3,值:1(错误,应为0)

1 个答案:

答案 0 :(得分:2)

我不确定我是否理解你的问题,但也许......

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