首页 > 解决方案 > 如何针对另一个匹配的字典键/值查询嵌套对象字典

问题描述

我需要查询对象内的字典并根据传入的字典带回某些记录。

我知道有一个.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

        }

标签: c#dictionary

解决方案


我们需要遍历所有的键/值对,queryDictionary并为列表中的每个项目匹配它们:

var results = list.Where(
    mf => queryDictionary.All(
        kvp => mf.Metadata.TryGetValue(kvp.Key, out var metdata) && metadata == kvp.Value
    )
);

推荐阅读