C# 如何按 list.count 排序字典 <string, list<string>>?
C# How to order dictionary<string, list<string>> by list.count?
我有一个 dictionary
,其中值是 list
个字符串。我想按每个 list
中的字符串数对字典进行排序。所以我打印的第一个kvp
是list
中元素数量最多的kvp
。
我在 Whosebug 的另一个问题下看到了这个答案,但我想我遗漏了什么。
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 上查看。
我有一个 dictionary
,其中值是 list
个字符串。我想按每个 list
中的字符串数对字典进行排序。所以我打印的第一个kvp
是list
中元素数量最多的kvp
。
我在 Whosebug 的另一个问题下看到了这个答案,但我想我遗漏了什么。
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 上查看。