KeyValuePair每个不同的值取n个结果

时间:2016-12-19 12:02:57

标签: c#

我有一个KeyValuePair,可以返回所有结果。我需要为每个值获取n个记录数。

所以如果我有哈利'和Sally',我需要Harry列出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>
}

但这只是让Harry和Sally回归,我无法解决必须在代码中添加take()

我该怎么做?

1 个答案:

答案 0 :(得分: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 . . .