您询问了列表、字典和包含其他字典的字典。
我最近有一个类似的话题,我想有一个可查询的字典(即允许将查询表达式作为 lambda 参数传递的扩展方法),您可以像这样使用:
var result = myDictionary.QueryDictionary(w => myList.Any(a => a == w.Key));
此代码行的目的是检查字典的任何键是否包含在 myList 中。
所以我做的是这样,我写了如下扩展方法:
// extension method using lambda parameters
public static Dictionary<string, T> QueryDictionary<T>(
this Dictionary<string, T> myDict,
Expression<Func<KeyValuePair<string,T>, bool>> fnLambda)
{
return myDict.AsQueryable().Where(fnLambda).ToDictionary(t => t.Key, t => t.Value);
}
它可以用于每个具有string 类型键和每个对象类型T 的项目的字典。
现在您可以通过传递 lambda 表达式轻松编写查询,如下例所示:
var list1 = new List<string>() { "a", "b" };
var myDict = new Dictionary<string, object>();
myDict.Add("a", "123"); myDict.Add("b", "456"); myDict.Add("c", "789");
var result = myDict.QueryDictionary(w => list1.Any(a => a == w.Key));
结果将包含项目 a 和 b,因为它们包含在 list1 中。
你也可以查询dictionary of dictionaries,这里是LinqPad的C#示例,但它也可以用作控制台应用程序(只需注释掉.Dump() 语句并将它们替换为 Console.WriteLine(...) 语句):
void Main()
{
// *** Set up some data structures to be used later ***
var list1 = new List<string>() { "a", "b", "d" }; // a list
var myDict = new Dictionary<string, object>(); // the dictionary
myDict.Add("a", "123"); myDict.Add("b", "456"); myDict.Add("c", "789");
var myDict2 = new Dictionary<string, object>(); // 2nd dictionary
myDict2.Add("a", "123"); myDict2.Add("b", "456"); myDict2.Add("c", "789");
myDict.Add("d", myDict2); // add 2nd to first dictionary
// *** 1. simple query on dictionary myDict ***
var q1 = myDict.QueryDictionary(w => list1.Any(a => a == w.Key));
q1.Dump();
// *** 2. query dictionary of dictionary (q3 contains result) ***
var q2 =
(Dictionary<string, object>)q1.QueryDictionary(w => w.Key.Equals("d")).First().Value;
var q3 = q2.QueryDictionary(w => w.Key.Equals("b"));
q3.Dump();
}
// *** Extension method 'QueryDictionary' used in code above ***
public static class Extensions
{
public static Dictionary<string, T> QueryDictionary<T>(
this Dictionary<string, T> myDict,
Expression<Func<KeyValuePair<string, T>, bool>> fnLambda)
{
return myDict.AsQueryable().Where(fnLambda).ToDictionary(t => t.Key, t => t.Value);
}
}
由于此方案使用泛型,您可以将任何 lambda 表达式作为搜索参数传递,因此非常灵活。