C#如何通过list.count命令dictionary >?
问题描述:
我有一个dictionary
其中的值是字符串的list
。我想按照每个list
中的字符串数量来排序字典。因此,我打印的第一张kvp
是list
中元素数最多的kvp
。C#如何通过list.count命令dictionary <string,list <string>>?
我在另一个问题在这里看到了这个答案在stackoverflow,但我想我失去了一些东西。
foreach (var kvp in teams.OrderBy(x => x.Value.Count))
答
你很近,但它听起来像你想降:
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);
}
}
}
输出:
Team Long List has 4 items.
Team Medium List has 3 items.
Team Short List has 2 items.
检查出来的.NET Fiddle。
请问您可以发布您的代码 – maxspan