I would like to take a list of objects and convert it to a dictionary where the key is a field in the object, and the value is a list of a different field in the objects that match on the key. I can do this now with a loop but I feel this should be able to be accomplished with linq and not having to write the loop. I was thinking a combination of GroupBy and ToDictionary but have been unsuccessful so far.
Here’s how I’m doing it right now:
var samplesWithSpecificResult = new Dictionary<string, List<int>>();
foreach(var sample in sampleList)
{
List<int> sampleIDs = null;
if (samplesWithSpecificResult.TryGetValue(sample.ResultString, out sampleIDs))
{
sampleIDs.Add(sample.ID);
continue;
}
sampleIDs = new List<int>();
sampleIDs.Add(sample.ID);
samplesWithSpecificResult.Add(sample.ResultString, sampleIDs);
}
The farthest I can get with .GroupBy().ToDictionay() is Dictionary<sample.ResultString, List<sample>>.
Any help would be appreciated.
Try the following
The
GroupByclause will group everySampleinstance in the list by itsResultStringmember, but it will keep only theIdpart of each sample. This means every element will be anIGrouping<string, int>.The
ToDictionaryportion uses theKeyof theIGrouping<string, int>as the dictionary Key.IGrouping<string, int>implementsIEnumerable<int>and hence we can convert that collection of samples’Idto aList<int>with a call toToList, which becomes theValueof the dictionary for that givenKey.