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
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.)
See more on this question at Stackoverflow