Return list with more than one value stored in a dictionary using linq

c#, linq

Solution

The earliest you can apply a filter is after grouping and before creating a dictionary:

.GroupBy(o => o.Value, o => o.Index)
.Where(g => g.Count() > 1)
.ToDictionary(grp => grp.Key, grp => grp.ToList());

This should not need any explanation; it's most efficient in that it avoids adding the items you don't want in the dictionary in the first place.

If you wanted to keep the single-item lists but filter them out only some of the time, you 'd instead need to filter on the dictionary with

dict.Where(p => p.Value.Count > 1)

Your original attempt

.ToDictionary(grp => grp.Key, grp => grp.ToList())
.Where(m => m.Value.Count > 1);

did not work because, even though it's a perfectly reasonable thing to do, the type of the result produced by `Where` would be `IEnumerable<KeyValuePair<string, List<int>>>`. However, you are trying to assign this value to a variable typed as a concrete dictionary, which is a special case of an enumerable list of key-value pairs and the compiler has to stop you from doing that in order to guarantee type safety.

If you changed the type of `fieldNameList` to the above then this line would compile, but you would not be able to use the `IDictionary<K, V>` interface later on.

Problem

I have a dictionary defined as follow: `Dictionary<string, List<int>>` and I want to filter so that it will only entries where `List<Int>` has more than 1 value in it. The code below builds my dictionary correctly (thanks to Andrew Whitaker) ``` Dictionary<string, List<int>> fieldNameList = Mapping.Select(m => m.FieldName) .Select((c, i) => new { Value = c, Index = i }) .GroupBy(o => o.Value, o => o.Index) .ToDictionary(grp => grp.Key, grp => grp.ToList()); ``` but now I need to filter it down so that only list with more than one items in it will be included in the final dictionary. Would you mind explaining the extra filter as I'd like to understand what I'm doing wrong. I added `.Where(m => m.Value.Count > 1)` of the existing query thinking this would do the trick, but it's giving an "implicit convertion" error.

Original source

Related problems