Alan Kirby
Alan Kirby

Reputation: 23

Find the Biggest List in a Dictionary of Lists

Lets say I have:

Dictionary<string, List<string>> ourGroups = new Dictionary(string, List<string>>();

Dictionary contents (Key is based on a specific letter position as shown):

Key | Value | Total

-O- | "DOC", "HOP", "POP" | Total = 3
--- | "SIP", "PLZ", "SUZ", "UPS" | Total = 4

So key 2 contains our biggest list of values.

How would I place the biggest key Values into a separate list? What I tried:

List<string> finalGroup = new List<string>();    
finalGroup = ourGroups.Values.Max();

Obviously I'm not doing this correctly. A bit of explanation on how this works would be appreciated.

Upvotes: 0

Views: 61

Answers (2)

Anu Viswan
Anu Viswan

Reputation: 18155

If you intend to get the Key, which has Items in its Value (list), you could use

var keyWithMaxValue = ourGroups.Aggregate((l, item) => l.Value.Count > item.Value.Count ? l : item).Key;

If you need the Value (list)

var maxValue = ourGroups.Aggregate((l, item) => l.Value.Count > item.Value.Count ? l : item).Value;

Upvotes: 1

Gowri Pranith Kumar
Gowri Pranith Kumar

Reputation: 1685

You can use LINQ to sort by Values and select the first one like below .

var result =   ourGroups.OrderByDescending(s => s.Value.Count()).First().Value;

Upvotes: 2

Related Questions