c# - 如何针对另一个匹配的字典键/值查询嵌套对象字典
问题描述
我需要查询对象内的字典并根据传入的字典带回某些记录。
我知道有一个.ContainsKey()
,但我需要检查键/值是否匹配。
我认为它需要是一个KeyValuePair
,但是如何将 Dictionary<string, string> 转换为 KeyValuePair。
做这个的最好方式是什么?或者甚至有可能吗?
代码:
public class MyFiles
{
public int Id { get; set; }
public string FileName { get; set; }
public IDictionary<string, string> Metadata { get; set; } = new Dictionary<string, string>();
}
private void button1_Click(object sender, EventArgs e)
{
var list = new List<MyFiles>();
list.Add(new MyFiles
{
Id = 1,
FileName = "myTestfile.jpg",
Metadata = new Dictionary<string, string>
{
{ "FileSize", "599" },
{ "GroupId", "25" },
{ "TypeId", "Finance" },
}
});
list.Add(new MyFiles
{
Id = 2,
FileName = "myTestfile1.jpg",
Metadata = new Dictionary<string, string>
{
{ "FileSize", "748" },
{ "GroupId", "25" },
{ "TypeId", "HR" },
}
});
list.Add(new MyFiles
{
Id = 3,
FileName = "myTestfile2.jpg",
Metadata = new Dictionary<string, string>
{
{ "FileSize", "78" },
{ "GroupId", "78" },
{ "TypeId", "IT" },
}
});
list.Add(new MyFiles
{
Id = 4,
FileName = "myTestfile2.jpg",
Metadata = new Dictionary<string, string>
{
{ "FileSize", "783" },
{ "GroupId", "78" },
{ "TypeId", "IT" },
}
});
// Instance one ===========================================
var queryDictionary = new Dictionary<string, string>();
queryDictionary.Add("GroupId", "78");
queryDictionary.Add("TypeId", "IT");
// Expected results would be Ids: 3 and 4
// Instance two ===========================================
queryDictionary.Clear();
queryDictionary.Add("GroupId", "78");
queryDictionary.Add("FileSize", "783");
// Expected results would be Ids: 4
}
解决方案
我们需要遍历所有的键/值对,queryDictionary
并为列表中的每个项目匹配它们:
var results = list.Where(
mf => queryDictionary.All(
kvp => mf.Metadata.TryGetValue(kvp.Key, out var metdata) && metadata == kvp.Value
)
);
推荐阅读
- ios - 将类别与 UIResponder 一起使用 - 坏主意?
- angular-material - 使用角度材质的静态标题菜单
- r - purrr 的 map* 函数族中的计数器
- android - 滑翔无法加载时如何从内部内存加载图像
- angular - 如何加载多个 div 而不会以 Angular 4 冻结应用程序
- python - 如何将时间增量转换为日期时间?
- nginx - 如何配置我的 Heroku 应用程序以限制对特定服务器的 herokuapp.com 域的访问?
- asp.net-mvc - 使用 mvc 路由为操作设置别名
- c - 没有与连接的串行端口通信?
- android-studio - 无法在 Ubuntu 上启动 android studio