【问题标题】:Linq to Dictionary with key and a listLinq to Dictionary 带键和列表
【发布时间】:2015-09-22 12:36:33
【问题描述】:

我的数据在两个表中

Master Columns 
ID    MyDateTime 
1     07 Sept
2     08 Sept

上面的 MyDatetime 列具有唯一索引

Detail Columns
ID     Data1     Data2    Data3
1      a         b        c 
1      x         y        z
1      f         g        h
2      a         b        c

我想将其填充到字典中。我试过了

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 });

我希望字典中有两行

1, List of 3 rows as details
2, List of 1 row as details

我收到一个错误,它抱怨输入了两次字典的键。关键是主数据中唯一的日期时间

【问题讨论】:

    标签: c# linq dictionary


    【解决方案1】:

    这正是查找的用途 - 所以使用 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);
    

    (您不需要使用Distinct,并注意使用连接而不是第二个fromwhere 子句。)

    【讨论】:

    • 在哪里使用字典以及在哪里查找 jon?
    • @EhsanSajjad:使用字典进行“键到单值”映射,并查找“键到多值”映射(当您查询时;查找是不可变的,因此您可以)当你改变集合时不要使用它)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多