Reputation: 43
I have a dictionary
where the value is a list
of strings. And I want to order the dictionary by the number of strings in each list
. So the first kvp
I print is the kvp
with the highest number of elements in the list
.
I saw this answer under another question here in stackoverflow, but I think I am missing something.
foreach (var kvp in teams.OrderBy(x => x.Value.Count))
Upvotes: 0
Views: 1482
Reputation: 52280
You're very close, but it sounds like you want descending:
using System;
using System.Linq;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
var teams = new Dictionary<string, List<string>>();
teams.Add("Short List", new List<string> {"One","Two"});
teams.Add("Medium List", new List<string> {"One","Two", "Three"});
teams.Add("Long List", new List<string> {"One","Two", "Three", "Four"});
foreach (var kvp in teams.OrderByDescending(x => x.Value.Count))
{
Console.WriteLine("Team {0} has {1} items.", kvp.Key, kvp.Value.Count);
}
}
}
Output:
Team Long List has 4 items.
Team Medium List has 3 items.
Team Short List has 2 items.
Check it out on .NET Fiddle.
Upvotes: 2