如何使用字典';林克在c#中的s顶N值? Dictionary dict=newdictionary(){…};
我需要一个由LINQ过滤的字典类型的结果;过滤条件是:如何使用字典';林克在c#中的s顶N值? Dictionary dict=newdictionary(){…};,c#,linq,dictionary,C#,Linq,Dictionary,我需要一个由LINQ过滤的字典类型的结果;过滤条件是:如果TValue的count>CONST_MAX,那么TValue只返回top CONST_MAX项字典不维护顺序。您可能希望使用SortedDictionary获取前x项。尝试:如果您正在比较dic的值 Dictionary<string,List<string>> dict =new Dictionary<string,List<string>>(){...}; return mydic
如果TValue的count>CONST_MAX,那么TValue只返回top CONST_MAX项
字典
不维护顺序。您可能希望使用SortedDictionary
获取前x项。尝试:如果您正在比较dic的值
Dictionary<string,List<string>> dict =new Dictionary<string,List<string>>(){...};
return mydic
.Where(p => p.value == myvalue)
.ToDictionary(p => p.Key, p => p.Value);
使用Take()方法
return mydic
.Where(p => p.value == myvalue)
.ToDictionary(p => p.Key, p => p.Value);
字典颜色=新字典();
颜色。添加(“1”、“红色”);
颜色。添加(“2”、“黑色”);
颜色。添加(“3”、“绿色”);
颜色。添加(“4”、“黄色”);
var top2=颜色。取(2);
foreach(top2中的KeyValuePair颜色)
{
Console.WriteLine(“{0}-{1}”,color.Key,color.Value);
}
由于您的问题不清楚,我假设您正在寻找具有相同键的新词典,但每个值中只有前N项:
return mydic
.Where(p => p.value == myvalue)
.ToDictionary(p => p.Key, p => p.Value);
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);
}
你能重新措辞你的问题吗?我不清楚你在问什么,那么到目前为止你尝试了什么?如果只在特定条件为真时才需要返回前N项,那么可以使用TakeWhile()方法-