Cody
Cody

Reputation: 8944

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>

Upvotes: 4

Views: 7629

Answers (2)

Cody
Cody

Reputation: 8944

I found a way to do it, the_joric's answer was close but I had to explicitly call ToList() on the values.

var splitTimes = times.GroupBy(x => x.ProjCdId).ToDictionary(o => tr.GetProjCd(o.Key), o => o.ToList());

Upvotes: 2

the_joric
the_joric

Reputation: 12226

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()

Upvotes: 3

Related Questions