我认为你需要这样的东西:
Dictionary<string, List<string>> dupeLists = ...;
var ret = dupeLists.ToDictionary(c => c.Key, c => c.Value.Distinct().ToList());
这会将项目复制到一个新字典中,只获取值列表中每个项目的一个副本。
所以如果dupeLists 看起来像:
{
"first": ["1", "2", "3", "1"],
"second": ["2", "3", "4", "3"]
}
然后这将返回:
{
"first": ["1", "2", "3"],
"second": ["2", "3", "4"]
}
与这些列表中的唯一值相比,您的代码无法正常工作,因为它正在寻找唯一的列表。因为每个列表在内存中的不同位置(您知道这一点,因为修改一个不会修改另一个),所以由您的 GroupBy 调用产生的每个组将只有一个元素长。
最初的问题比现在清楚得多,所以我添加了几个变体以确保找到正确的答案。下面列出了这些以供后代使用,但事实证明它们不适用于这种特殊情况。
为了更好的衡量,你said you need to“摆脱重复值”,这是模棱两可的。如果你想扔掉任何有重复的东西,
Dictionary<string, List<string>> dupeLists = ...;
var ret = dupeLists.ToDictionary(c => c.Key, c => c.Value.GroupBy(x => x)
.Where(x => x.Count() == 1)
.Select(x => x.Key)
.ToList());
将返回:
{
"first": ["2", "3"],
"second": ["2", "4"]
}
既然你在情绪低落的日子里抓住了我,如果你真的想返回一个不同项目的平面列表,
Dictionary<string, List<string>> dupeLists = ...;
var ret = dupeLists.SelectMany(c => c.Value).Distinct().ToList();
产生:
["1", "2", "3", "4"]
或者只是在整个字典中只出现一次的那些:
Dictionary<string, List<string>> dupeLists = ...;
var ret = dupeLists
.SelectMany(c => c.Value)
.GroupBy(c => c)
.Where(c => c.Count() == 1)
.Select(c => c.Key)
.ToList();
这是:
["4"]
或者只是那些只出现在任何给定列表中,而没有其他列表的:
Dictionary<string, List<string>> dupeLists = ...;
var ret = dupeLists
.SelectMany(c => c.Value, (kvp, Value) => new { kvp.Key, Value })
.GroupBy(c => c.Value)
.Where(c => c.Select(x => x.Key).Distinct().Count() == 1)
.GroupBy(c => c.Key, c => c.Value)
.ToDictionary(c => c.Key, c => c.ToList());
如果我的未经测试的代码成立的话:
{
"first": ["1", "1"],
"second": ["4"]
}