2016-12-19 61 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 –