您可以按以下顺序通过一系列链式 LINQ 查询来完成此操作:
-
GroupBy() - 这将为您的每个用户创建组,以避免在创建字典时出现问题(即重复键)。
-
ToDictionary() - 此方法可以使用键和值绑定给定的数据集,因为您已经有了键(通过之前的调用),您只需要从每个组。
-
SelectMany() - 这将从您之前的组中选择所有单独的值,实质上是将每组用户的所有项目合并到一个集合中。
-
Distinct() - 这将应用于上一步中生成的字符串列表以删除任何重复项。如果您想允许重复,只需删除此步骤即可。
实现这一点类似于以下 sn-p 代码:
// 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。