Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq to Dictionary with key and a list

My data is as under in two tables

Master Columns 
ID    MyDateTime 
1     07 Sept
2     08 Sept

MyDatetime column in above has unique index

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

I want to populate this in a dictionary. I have tried

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

I expect two rows in the dictionary

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

I get an error where it complains about the key of the dictionary entered twice. The key would be the datetime which is unique in the master

like image 462
Jack Gray Avatar asked Sep 22 '15 12:09

Jack Gray


Video Answer


1 Answers

This is precisely what lookups are for - so use ToLookup instead of 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);

(You shouldn't need to use Distinct, and note the use of a join instead of a second from and a where clause.)

like image 52
Jon Skeet Avatar answered Oct 11 '22 00:10

Jon Skeet