Search code examples
c#linqentity-framework-6

Create a one to many collection from linq result setC#


I have a database table which contains one to many data collection. From that table I need to make a dictionary which represents the data. the key will be the master Id and the values will be the ids associated to that master id. my dataset is like the following

and the expected dictionary should be like the following

enter image description here

I tried the following code but it didnt work as expected. Instead of Dictionary<int,List> it returned Dictionary<key,groupbydata collection>.

 Table.GroupBy(item => item.MasterId).ToDictionary(item => item.Key);

Any thoughts?


Solution

  • You need to cast the values inside the grouping to the dictionary

    var test = Table.GroupBy(item => item.MasterId).ToDictionary(g => g.Key, v=> v.Select(x => x.InternalValue));
    

    so you got a Dictionary<MasterID, IEnumerable >