[英]how to take dictionary's top N values in c# by linq?
Dictionary<string,List<string>> dict =new Dictionary<string,List<string>>(){...};
I need a result of dictionary type that filtered by LINQ; 我需要一个由LINQ过滤的字典类型的结果; the filter condition is:
if TValue's count > CONST_MAX, then TValue only return top CONST_MAX items
. 过滤条件为:
if TValue's count > CONST_MAX, then TValue only return top CONST_MAX items
。
Dictionary<TKey, TValue>
doesn't maintain order. Dictionary<TKey, TValue>
不维护顺序。 You might want to use SortedDictionary<TKey, TValue>
for getting top x items. 您可能要使用
SortedDictionary<TKey, TValue>
来获取前x个项目。
Since your question is unclear, I'm going to assume you're looking for a new dictionary with the same keys, but only the first N items in each value: 由于您的问题尚不清楚,因此我假设您正在寻找具有相同键的新字典,但每个值中只有前N个项:
var firstN = dict.ToDictionary(
kvp => kvp.Key,
kvp => kvp.Value.Take(CONST_MAX).ToList());
try : if you are comparing value of dic 尝试:如果您正在比较dic的值
return mydic
.Where(p => p.value == myvalue)
.ToDictionary(p => p.Key, p => p.Value);
Use the Take() method 使用Take()方法
Dictionary<string, string> colours = new Dictionary<string, string>();
colours.Add("1", "Red");
colours.Add("2", "Black");
colours.Add("3", "Green");
colours.Add("4", "Yellow");
var top2 = colours.Take(2);
foreach (KeyValuePair<string, string> colour in top2)
{
Console.WriteLine("{0}-{1}", colour.Key, colour.Value);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.