在List< Dictionary< string,object>中搜索值. [英] Search for a value in List<Dictionary<string, object>>

查看:72
本文介绍了在List< Dictionary< string,object>中搜索值.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 List<字典<字符串,对象>> 变量,如下所示.

I have a List< Dictionary < string, object >> variable as follows.

private static List<Dictionary<string, object>> testData = new List<Dictionary<string, object>>(100);

// Just Sample data for understanding.
for (int i = 0; i < 100; i++)
{
    var test = new Dictionary<string, object>
        {
            { "aaa", "aaa" + i % 4 },
            { "bbb", "bbb" + i % 4 },
            { "ccc", "ccc" + i % 4 },
            { "ddd", "ddd" + i % 4 },
            { "eee", "eee" + i % 4 },
            { "fff", "fff" + i % 4 },
            { "ggg", "ggg" + i % 4 },
            { "hhh", "hhh" + i % 4 },
            { "iii", "iii" + i % 4 }
        };
    testData.Add(test);
}

我想在字典中搜索键,值的列表,然后返回 List<字典<字符串,对象>> 包含我传递的searchPattern.

I want to search for a list of key,value in the Dictionary and return the List< Dictionary < string, object >> contains the searchPattern I passed.

Dictionary<string, object> searchPattern = new Dictionary<string, object>();
searchPattern .Add("aaa", "aaa4");
searchPattern .Add("eee", "eee2");
searchPattern .Add("fff", "fff1");
searchPattern .Add("ddd", "ddd3");


public List<Dictionary<string, object>> SearchList(List<Dictionary<string, object>> testData, Dictionary<string, object> searchPattern)
{
    List<Dictionary<string, object>> result;

    // Search the list.

    return result;
}

对搜索的其他任何建议也表示赞赏.非常感谢!

Any other suggestions to search also appreciated. Many Thanks!!

推荐答案

这将返回列表中包含搜索模式中所有键值对的第一个词典,如果没有则返回 null 不是一个.

This will return the first dictionary in the list that contains all the key-value pairs in search pattern, or null if there isn't one.

public Dictionary<string, object> SearchList
(
    List<Dictionary<string, object>> testData,
    Dictionary<string, object> searchPattern
)
{
    return testData.FirstOrDefault(x => searchPattern.All(x.Contains));
}

如果要所有匹配项(而不仅仅是第一个匹配项),请使用 Where([...]).ToList()而不是 FirstOrDefault([...]).

If you want all the matches (not just the first one) use Where([...]).ToList() instead of FirstOrDefault([...]).

这篇关于在List&lt; Dictionary&lt; string,object&gt;中搜索值.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆