2 回答
TA贡献1943条经验 获得超7个赞
您可以用扁平化您的字典SelectMany并获得看起来像的简单列表
"a" - "Red"
"a" - "Yellow"
"b" - "Blue"
"b" = "Red"
// and so on
然后按值分组并从这些组中构建一个新字典。试试这个代码:
var commonValues = dict.SelectMany(kv => kv.Value.Select(v => new {key = kv.Key, value = v}))
.GroupBy(x => x.value)
.Where(g => g.Count() > 1)
.ToDictionary(g => g.Key, g => g.Select(x => x.key).ToList());
TA贡献1853条经验 获得超6个赞
很多循环......循环遍历字典,然后循环遍历列表中的每个值。
var result = new Dictionary<string, List<string>>();
// Loop through each key/value pair in the dictionary
foreach (var kvp in dict)
{
// kvp.Key is the key ("a", "b", etc)
// kvp.Value is the list of values ("Red", "Yellow", etc)
// Loop through each of the values
foreach (var value in kvp.Value)
{
// See if our results dictionary already has an entry for this
// value. If so, grab the corresponding list of keys. If not,
// create a new list of keys and insert it.
if (!result.TryGetValue(value, out var list))
{
list = new List<string>();
result.Add(value, list);
}
// Add our key to this list of keys
list.Add(kvp.Key);
}
}
如果您想通过包含多个项目的条目来过滤它,那么您可以执行以下操作:
result = result.Where(x => x.Value.Count > 1).ToDictionary(x => x.Key, x => x.Value);
或者,您可以避免循环并改用 Linq:
// Flatten the dictionary into a set of tuples
// e.g. (a, Red), (a, Yellow), (b, Blue), (b, Red), etc
var result = dict.SelectMany(kvp => kvp.Value.Select(color => (key: kvp.Key, color)))
// Group by the value, taking the color as the elements of the group
// e.g. (Red, (a, b)), (Yellow, (a)), etc
.GroupBy(item => item.color, item => item.key)
// Filter to the ones with more than one item
.Where(group => group.Count() > 1)
// Turn it into a dictionary, taking the key of the grouping
// (Red, Green, etc), as the dictionary key
.ToDictionary(group => group.Key, group => group.ToList());
您还可以使用 linq 查询语法,该语法稍长,但避免了SelectMany:
var result =
(
from kvp in dict
from color in kvp.Value
group kvp.Key by color into grp
where grp.Count() > 1
select grp
).ToDictionary(grp => grp.Key, grp => grp.ToList());
- 2 回答
- 0 关注
- 92 浏览
添加回答
举报