[英]how to take dictionary's top N values in c# by linq?
Dictionary<string,List<string>> dict =new Dictionary<string,List<string>>(){...};
我需要一个由LINQ过滤的字典类型的结果; 过滤条件为: if TValue's count > CONST_MAX, then TValue only return top CONST_MAX items
。
Dictionary<TKey, TValue>
不维护顺序。 您可能要使用SortedDictionary<TKey, TValue>
来获取前x个项目。
由于您的问题尚不清楚,因此我假设您正在寻找具有相同键的新字典,但每个值中只有前N个项:
var firstN = dict.ToDictionary(
kvp => kvp.Key,
kvp => kvp.Value.Take(CONST_MAX).ToList());
尝试:如果您正在比较dic的值
return mydic
.Where(p => p.value == myvalue)
.ToDictionary(p => p.Key, p => p.Value);
使用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.