【问题标题】:LINQ left join with group by and correct countLINQ left join with group by 并正确计数
【发布时间】:2016-12-04 16:13:15
【问题描述】:

是否存在其他计算方法?

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 包含像

这样的标题

标题 1:ID = 1,文本 = Text1(来自配置文件 1)
Headword2:ID = 2,Text = Text2(来自 Profile 1)
Headword1:ID = 1,Text = Text1(来自 配置文件 2)

方法列表包含

标题 1:ID = 1,文本 = 文本 1
标题 2:ID = 2,文本 = 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 => y != null 不能正常工作! 我明白了:

键:Text1,值:2
键:Text2,值:1
Key:Text3,Value:1(错误,应该是0)

【问题讨论】:

  • 那些QueryOver 方法实际上是返回列表吗?如果您将其保留为 IQueryable,则可以更好地优化它。

标签: c# linq


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-26
    • 1970-01-01
    • 2017-05-14
    相关资源
    最近更新 更多