2016-12-19 27 views
0

我有一个KeyValuePair,它返回所有结果。我需要为每个值取n的记录数。KeyValuePair取不同值的n个结果

所以,如果我有“哈利”和“莎莉”,我需要哈利上市5个号码的时间和Sally 5数次

目前,我有这样的:

var organiser = new List<KeyValuePair<string, string>>(); 
foreach(someinfo) 
{ 
    organiser.Add(new KeyValuePair<string, string>("Name", Name)); 
} 
foreach (var p in organiser.GroupBy(KeyValuePair =>KeyValuePair.Value)) 
{ 
    <p>@p.Key</p> 
} 

但这只是返回哈利和莎莉,我不能工作必须添加take()的代码。

我该怎么做?

+5

一个问题,虽然。为什么在使用字典时使用KeyValuePairs的列表?如果有的话,你可以使用一个'Dictionary >',它附带了预先分组的名称。 – Abion47

回答

1

使用一些LINQ中,集团通过密钥,然后以5:

var data = new List<KeyValuePair<string, string>> 
{ 
    new KeyValuePair<string, string>("Harry", "1"), 
    new KeyValuePair<string, string>("Harry", "2"), 
    new KeyValuePair<string, string>("Harry", "3"), 
    new KeyValuePair<string, string>("Harry", "4"), 
    new KeyValuePair<string, string>("Harry", "5"), 
    new KeyValuePair<string, string>("Harry", "6"), 
    new KeyValuePair<string, string>("Harry", "7"), 
    new KeyValuePair<string, string>("Sally", "1"), 
    new KeyValuePair<string, string>("Sally", "2"), 
    new KeyValuePair<string, string>("Sally", "3"), 
    new KeyValuePair<string, string>("Sally", "4"), 
    new KeyValuePair<string, string>("Sally", "5"), 
    new KeyValuePair<string, string>("Sally", "6"), 
}; 


var output = data.GroupBy(x => x.Key) 
    .SelectMany(x => x.Take(5)); 

foreach (var item in output) 
{ 
    Console.WriteLine($"Key: {item.Key}, Value: {item.Value}"); 
} 

输出将是

Key: Harry, Value: 1 
Key: Harry, Value: 2 
Key: Harry, Value: 3 
Key: Harry, Value: 4 
Key: Harry, Value: 5 
Key: Sally, Value: 1 
Key: Sally, Value: 2 
Key: Sally, Value: 3 
Key: Sally, Value: 4 
Key: Sally, Value: 5 
Press any key to continue . . . 
+0

谢谢Kevin Smith –