简体   繁体   中英

Transfor List to Nested Dictionary using linq C#

I have a list that contains data like this

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

I want to create a Dictionary like this:

Dictionary<int, Dictionary<string,int>
Dictionary<ID, Dictionary<START_DATE.Date, Total of owners>

Where the result stay in this way.

ID
1
    START_DATE      | TOTAL
    01/03/2013          2
    02/03/2013          1
ID
2
    START_DATE      | TOTAL
    01/03/2013          1

Is There a way to do this with linq using C#?

You can try this with a pair of GroupBy and a pair of calls of ToDictionary , like this:

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

If you would like to also add the total time per day, you can do this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM