Cross list nested dictionary using linq C #

I have a list containing 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 remains that 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 #?

+4
source share
1 answer

You can try this with a GroupBy pair and a ToDictionary call ToDictionary , for example:

 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 want 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) } ); 
+6
source

Source: https://habr.com/ru/post/1486233/


All Articles