Linq to Dictionary with key和list

Jac*_*ray 5 c# linq dictionary

我的数据如下表所示

Master Columns 
ID    MyDateTime 
1     07 Sept
2     08 Sept
Run Code Online (Sandbox Code Playgroud)

上面的MyDatetime列具有唯一索引

Detail Columns
ID     Data1     Data2    Data3
1      a         b        c 
1      x         y        z
1      f         g        h
2      a         b        c
Run Code Online (Sandbox Code Playgroud)

我想在字典中填充这个.我试过了

Dictionary<DateTime, List<Detail>> result = (
                          from master in db.master
                          from details in db.detail
                          where (master.ID == detail.ID)
                          select new
                          {
                              master.MyDateTime,
                              details
                          }).Distinct().ToDictionary(key => key.MyDateTime, value => new List<Detail> { value.details });
Run Code Online (Sandbox Code Playgroud)

我希望字典中有两行

1, List of 3 rows as details
2, List of 1 row as details
Run Code Online (Sandbox Code Playgroud)

我得到一个错误,它抱怨输入两次字典的键.关键是日期时间在主服务器中是唯一的

Jon*_*eet 10

这正是查找的用途 - 因此请使用ToLookup而不是ToDictionary:

ILookup<DateTime, Detail> result =
    (from master in db.master
     join details in db.detail on master.ID equals detail.ID
     select new { master.MyDateTime, details })
    .ToLookup(pair => pair.MyDateTime, pair => pair.details);
Run Code Online (Sandbox Code Playgroud)

(您不应该使用Distinct,并注意使用连接而不是第二个from和一个where子句.)

  • @EhsanSajjad:使用字典作为"单值键"映射,并查找"多值键"映射(当您查询时;查找是不可变的,因此当您进行变异时不能使用它集合). (3认同)