c# - 如何从字典中获取不匹配的列表
问题描述
我想根据使用 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 的字典。
解决方案
基于仅应忽略其中一个字典中的项目的假设:
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);
推荐阅读
- python - 在 Figma 上显示实时图表
- java - Java 客户端-服务器:“While loop”问题
- php - 页面刷新时如何防止 PHP SESSION 关闭?
- java - 通过 jdbcTemplate.query 将 Date 或 LocalDate 注入 SQL 查询?
- angular - 验证器指令正在捕获旧输入值而不是新输入值
- angular - 在角度库中包含 css 文件
- javascript - 是否可以防止在修复画布之外创建网格项目?
- css - 如何使用 CSS 在鼠标悬停时缩放图像?
- apache-kafka - Kafka-Connect 启动时 Kafka-Connect 服务日志中的 NullPointerException
- java - 如何从 DynamoDB 表中的项目中删除属性?