c# - LINQ 左连接与分组依据和正确计数

标签 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 (from Profile 1)
Headword2: ID = 2, Text = Text2 (from Profile 1)
Headword1: ID = 1, Text = Text1 (from Profile 2)

方法列表包含

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

我想制作一个像这样的字典

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

这不起作用!我刚刚得到

Key: Text1, Value: 2
Key: Text2, Value: 1
in my Dictionary. Now i improved to with left join:

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 无法正常工作! 我得到:

Key: Text1, Value: 2
Key: Text2, Value: 1
Key: Text3, Value: 1 (wrong, should be 0)

最佳答案

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

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

关于c# - LINQ 左连接与分组依据和正确计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38667370/

相关文章:

c# - 通过 linq 复制行

c# - 使用泛型和 LINQ 的 MVC3 HtmlHelpers

c# - 您如何正确测试 MVVM 中的 View ?

c# - 参数化sql查询问题

c# - 如何将 DynamoDB 属性设置为空列表?

c# - LINQ 查询根据匹配的另一个表从一个表返回

c# - 如何在 LINQ 中选择查询时存储变量?

c# - IEnumerable<Func<T,S>> 和 LINQ 类型推断

c# - 进程退出问题线程未成功退出

c# - 在 C# 2.0 中使用关键字 var 不好吗?