Dictionary<string,List<string>> dict =new Dictionary<string,List<string>>(){...};
I need a result of dictionary type that filtered by LINQ; the filter condition is: if TValue's count > CONST_MAX, then TValue only return top CONST_MAX items
.
Dictionary<TKey, TValue>
doesn't maintain order. You might want to use SortedDictionary<TKey, TValue>
for getting top x items.
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:
var firstN = dict.ToDictionary(
kvp => kvp.Key,
kvp => kvp.Value.Take(CONST_MAX).ToList());
try : if you are comparing value of dic
return mydic
.Where(p => p.value == myvalue)
.ToDictionary(p => p.Key, p => p.Value);
Use the Take() method
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);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.