使用LINQ C#将列表转换为嵌套字典

4
我有一个包含以下数据的列表:
ID  |   START_DATE          |   END_DATE                |   Chapter     |   ID_OWNER
1       01/03/2013 05:15:14     01/03/2013 06:20:14         1               1
1       01/03/2013 06:25:33     01/03/2013 06:40:11         2               1
1       01/03/2013 05:15:14     01/03/2013 06:20:15         1               2
1       01/03/2013 06:25:33     01/03/2013 06:40:18         2               2   
2       01/03/2013 05:01:34     01/03/2013 05:30:13         1               3
2       01/03/2013 05:31:20     01/03/2013 06:30:13         2               3
2       01/03/2013 06:32:20     01/03/2013 07:20:01         3               3
1       02/03/2013 05:15:14     01/03/2013 06:20:14         1               1
1       02/03/2013 06:25:33     01/03/2013 06:40:11         2               1

我想创建一个像这样的字典:
Dictionary<int, Dictionary<string,int>
Dictionary<ID, Dictionary<START_DATE.Date, Total of owners>

结果就会保持这个状态。
ID
1
    START_DATE      | TOTAL
    01/03/2013          2
    02/03/2013          1
ID
2
    START_DATE      | TOTAL
    01/03/2013          1

有没有使用C#中的LINQ来实现这个的方法?
1个回答

6
您可以尝试使用一对GroupBy和一对ToDictionary来实现,代码如下:
var res = list
    .GroupBy(v => v.ID)
    .ToDictionary(
        g => g.Key
    ,   g => g.GroupBy(v => v.START_DATE.Date)
        .ToDictionary(h => h.Key, h => h.Seelct(x => x.ID_OWNER).Distinct().Count())
    );

如果您想每天添加总时间,可以这样做:
var res = list
    .GroupBy(v => v.ID)
    .ToDictionary(
        g => g.Key
    ,   g => g.GroupBy(v => v.START_DATE.Date)
        .ToDictionary(h => h.Key, h => new {
             Count = h.Seelct(x => x.ID_OWNER).Distinct().Count())
         ,   TotalTime = h.Sum(h => x.END_DATE-x.START_DATE)
         }
    );

我尝试过了,但它无法编译,我收到了一条关于行g.GroupBy的消息:“当前上下文中不存在名称g”。 - Renato Ramos Nascimento
@RenatoRamosNascimento 现在应该可以编译了。 - Sergey Kalinichenko
@RenatoRamosNascimento 当然可以。如果您需要包含其他数据,则Dictionary<int,Dictionary<string,int>>的结构需要更改。 - Sergey Kalinichenko
@dasblinkenlight 是的,它运行得很好,我只想在结果中添加持续时间。 - Renato Ramos Nascimento
@RenatoRamosNascimento 你尝试过使用“TotalTime”进行第二个查询了吗?它有效吗? - Sergey Kalinichenko
显示剩余6条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接