Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List of EF objects to Dictionary of lists using linq

I'd like to convert a list of EF objects to a dictionary. I somewhat accomplished this, with one drawback: I can't figure out how to add multiple of the objects to one key,value pair based on an attribute of that object.

For example say I have an Entity Framework object TblValue with three values - ValueID, ValueNm, CodeID.

The CodeID will be shared among the objects - some may be the same and some may be different.

I would like to create a Dictionary<TblCode, List<TblData>>. (TblCode comes from CodeID.) Basically, I want to create a dictionary of this list of items where each list is separated & grouped by the CodeID, using LINQ.

The LINQ statement I was using before was working, but it wouldn't do any grouping. Is this pretty close, or is LINQ not appropriate for this? Would a foreach loop be better?

var splitTimes = times.Cast<TblValue>().ToDictionary(o => tr.GetCode(o.CodeID));

clarification - I am unable to group the values....I cannot create a Dictionary<TblCode, List<TblValue>>, I can only create a Dictionary<TblCode, TblValue>

like image 362
Cody Avatar asked Oct 28 '25 12:10

Cody


1 Answers

You need to first group and then convert to dictionary. Like that:

var dictionary = tblValues
      .GroupBy(table => table.CodeID)
      .ToDictionary(values => values.Key);

If you need to convert you key do it in either GroupBy() or ToDictionary()

like image 79
the_joric Avatar answered Oct 30 '25 01:10

the_joric



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!