在 List<Dictionary<string, object>> 中搜索值

Ram*_*rai 5 c# search dictionary list .net-4.0

我有一个List< Dictionary < string, object >>变量如下。

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);
}
Run Code Online (Sandbox Code Playgroud)

我想在字典中搜索键值列表并返回List< Dictionary < string, object >>包含我传递的 searchPattern 。

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;
}
Run Code Online (Sandbox Code Playgroud)

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

ver*_*ald 2

这将返回列表中包含搜索模式中所有键值对的第一个字典,或者null如果没有的话。

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

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