首页 > 解决方案 > 如何从字典中获取不匹配的列表

问题描述

我想根据使用 LINQ 的列表项获得不匹配的字典。请参考我的示例代码

Dictionary<string, List<int>> lowerActionRoles = new Dictionary<string, List<int>>();
Dictionary<string, List<int>> upperActionRoles = new Dictionary<string, List<int>>();

lowerActionRoles.Add("11", new List<int>() { 1, 2, 4 });
upperActionRoles.Add("11", new List<int>() { 1, 2, 4, 5 });
lowerActionRoles.Add("13", new List<int>() { 1, 2, 4 });

lowerActionRoles.Add("21", new List<int>() { 1, 2, 4 });
upperActionRoles.Add("21", new List<int>() { 1, 2, 4 });

在这里,我有 2 个字典 lowerActionRoles 和 upperActionRoles。键 21 匹配但键 11 不匹配的字典。在这里,我想获取键为 11 的字典。

标签: c#linq

解决方案


基于仅应忽略其中一个字典中的项目的假设:

lowerActionRoles.Where(entry =>
{
    if (upperActionRoles.TryGet(entry.Key, out List<int> upperActionList))
    {
        return !upperActionList.SequenceEqual(entry.Value);
    }
    else
    {
        return false;
    }
}

lowerActionRoles这将为您返回( IEnumerable<KeyValuePair<string, List<int>>>)中的条目集合。

如果您只对键感兴趣,请添加

.Select(entry => entry.Key);

到上一个查询

并转换为新字典:

.ToDictionary(entry => entry.Key, entry => entry.Value);

推荐阅读