我有一个定义的字典,如下所示:

Dictionary<int, Dictionary<string, object>> dict = new Dictionary<..>();

以及用于添加数据的示例代码:

dict.Add (X, new Dictionary<string, object> ());
dict [X].Add ("Car", CarObject);
dict [X].Add ("Seller", SellerObject);
dict [X].Add ("Key3", Z);

我想在内部字典中搜索,如果它包含一个对象,然后该对象包含以下键“ Car”的CarObject.Name = (wildcard)X1(wildcard) ,但我似乎无法掌握如何获取进入内部字典,然后使用LINQ进入对象以搜索值。

===============>>#1 票数:1

这将返回所有匹配的KeyValuePair<string, object>

var query = dict.SelectMany(d => d.Value)
                .Where(i => i.Key == "Key1"
                    && (
                          i.Value is CarObject
                          ? ((CarObject)i.Value).Name.Contains("X1")
                          : false
                       ));

===============>>#2 票数:0

请尝试以下操作:

var results = dict[X].Where(x => (x.Value is CarObject) && ((CarObject)x.Value).Name.Contains("X1"));

如果只想获取值而不是字典并打印值,则可以执行以下操作:

int X = 0, Z = 1;
dict[X].Add("Key1", CarObject);
dict[X].Add("Key2", SellerObject);
dict[X].Add("Key3", Z);

var results = dict[X].Where(x => (x.Value is CarObject) && ((CarObject)x.Value).Name.Contains("X1")).Select(x => x.Value);
foreach (var str in results)
   Console.WriteLine(str);

===============>>#3 票数:0

您可以尝试如下操作:

dict[X].Where(x => x.Value is CarObject && ((CarObject)x.Value).Name.Contains("X1"));

要么:

dict[X].Values.OfType<CarObject>().Any(x => x.Name.Contains("X1"))

  ask by Richard translate from so

未解决问题?本站智能推荐:

关注微信公众号