Reputation: 4610
I want to be able to group a list of items by a particular field (id) and then extract a dictionary of id,code pairs. I then need to access the id and code pairs to do some logic. how can i do this using linq?
e.g.
Id Code Send
1 500 1
1 501 0
2 600 1
2 601 0
2 602 0
3 700 0
3 701 1
3 702 0
3 703 1
Expected Result -
1 500,501
2 600,601,602
3 700, 701, 702, 703
This is what i have so far - struggling to work out how to get just the codes into a dictionary:
from i in items
group i by i.Id into g
select new Dictionary<Guid, List<long>>
{
g.Key, g.ToList()
}
Upvotes: 1
Views: 104
Reputation: 117019
It seems to me that LINQ has an operator that does this already.
ILookup<Guid, long> res = items.ToLookup(i => i.Id, i => i.Code);
Upvotes: 0
Reputation: 12956
the last part
g.ToList()
needs to be
g.Select(c => c.Code).ToList()
Upvotes: 1
Reputation: 726479
You can do it like this:
var res = items
.GroupBy(i => i.Id)
.ToDictionary(
g => g.Key
, g => g.Select(v => v.Code).ToList()
);
Your solution was close - you needed to add a selection of Code
to complete it.
Upvotes: 1