您可以通过以下顺序的一系列链式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