您可以通過以下順序的一系列鏈式LINQ查詢做到這一點:
GroupBy()
- 這將創建每個單獨的用戶羣,以避免出現問題創建字典時(即重複密鑰)。
ToDictionary()
- 此方法將使用鍵和值綁定給定的一組數據,因爲您已經有了鍵(通過先前的調用),您只需從每個組中獲取值。
SelectMany()
- 這將選擇您之前的組中的所有單個值,實質上是將每組用戶中的所有項目合併到一個集合中。
Distinct()
- 這將應用在上一步中生成的字符串列表中,以刪除任何重複項。如果你想允許重複,只需刪除這一步。
實現這個看起來像下面的代碼片段:
// Group the collections by user and then select the keys based on those users
var dictionary = list.GroupBy(l => l.Key)
.ToDictionary(
x => x.Key,
x => x.SelectMany(l => l.Value)
.Distinct()
.ToList()
);
例
// Example of your existing data
var list = new List<KeyValuePair<string, List<string>>>(){
new KeyValuePair<string,List<string>>("User 1", new List<string>(){ "trigger1" ,"trigger2", "trigger3" }),
new KeyValuePair<string,List<string>>("User 2", new List<string>(){ "trigger1" ,"trigger2" }),
new KeyValuePair<string,List<string>>("User 3", new List<string>(){ "trigger2" ,"trigger3", "trigger4" }),
new KeyValuePair<string,List<string>>("User 1", new List<string>(){ "trigger0" ,"trigger4" }),
};
// Group the collections by user and then select the keys based on those users
var dictionary = list.GroupBy(l => l.Key)
.ToDictionary(
x => x.Key,
x => x.SelectMany(l => l.Value)
.Distinct()
.ToList()
);
// Output each key with it's associated values
foreach(var key in dictionary.Keys)
{
Console.WriteLine("Key: " + key + ", Values: " + String.Join(",",dictionary[key].ToArray()));
}
// Example output
// Key: User 1, Values: trigger1,trigger2,trigger3,trigger0,trigger4
// Key: User 2, Values: trigger1,trigger2
// Key: User 3, Values: trigger2,trigger3,trigger4
你可以see an interactive version of this here。
看起來不錯,但我不需要list1.Concat(列表2),因爲我只有1名名單。 – FailedUnitTest
@FailedUnitTest我認爲你的KVP來自不同的來源。謝謝! – dasblinkenlight