Convert List to Dictionary

Try the following

var dictionary = sampleList
    .GroupBy(x => x.ResultString, x => x.ID)
    .ToDictionary(x => x.Key, x => x.ToList());

The GroupBy clause will group every Sample instance in the list by its ResultString member, but it will keep only the Id part of each sample. This means every element will be an IGrouping<string, int>.

The ToDictionary portion uses the Key of the IGrouping<string, int> as the dictionary Key. IGrouping<string, int> implements IEnumerable<int> and hence we can convert that collection of samples’ Id to a List<int> with a call to ToList, which becomes the Value of the dictionary for that given Key.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)