【问题标题】:Extract record from dictionary list where key and value does not contains given value list c#从字典列表中提取记录,其中键和值不包含给定值列表c#
【发布时间】:2020-03-02 06:49:21
【问题描述】:
List<Dictionary<string, string>> firstList = new List<Dictionary<string, string>>();   
Dictionary<string, string> dict = new Dictionary<string,string>();
dict.Add("name", "abc");
dict.Add("age", "22");
dict.Add("address", "xyz,aa");
dict.Add("contact", "111");
firstList .Add(dict);
Dictionary<string, string> dict2 = new Dictionary<string,string>();
dict2 .Add("name", "pqr");
dict2 .Add("age", "25");
dict2 .Add("address", "xxx,bb");
dict2 .Add("contact", "4222");
firstList .Add(dict2);
Dictionary<string, string> dict3 = new Dictionary<string,string>();
dict3 .Add("name", "aa");
dict3 .Add("age", "24");
dict3 .Add("address", "xxx,aa");
dict3 .Add("contact", "aaa");
firstList .Add(dict3);

返回列表不包含 key = 'address' 和 name= 'aa' 的记录

更新:- 返回记录,其中 name='aa'

【问题讨论】:

  • 为什么你有(很多)具有相同键的字典,而不是具有(正确键入)属性NameAgeint)、Address 和 @ 的专用类987654327@?如果您需要通过string 键访问它,您始终可以实现Indexer。但是一个专门的类通常比一堆“字符串类型”的字典引起的头痛要少得多。 -- 然后会变成list.Where(item =&gt; item.Address is null &amp;&amp; item.Name == "aa");
  • @Dale 我正在使用动态列表,所以我无法指定具有属性的专用类,并且我不知道如何创建属性是动态的通用专用类,所以我使用字典

标签: c# asp.net-mvc linq dictionary


【解决方案1】:

使用 linq 非常简单:

var result = firstList.Where(x => !(x.ContainsKey("address") 
                                && x.ContainsKey(name)
                                && x["name"] == "aa")).ToList();

如果只需要一条记录,则使用FirstOrDefault():

var result = firstList.Where(x => !(x.ContainsKey("address") 
                                && x.ContainsKey(name)
                                && x["name"] == "aa")).FirstOrDefault();

别忘了加在上面:

using System.Linq;

UDPATE:

var result = firstList.Where(x => 
                                && x.ContainsKey(name)
                                && x["name"] != "aa")).FirstOrDefault();

【讨论】:

  • 实际上我需要那些键是'name'并且值不等于'aa'的记录
  • @shahbazusmani 您需要相应地更新您的状况,查看更新后的答案
  • 谢谢你更新的答案对我有用,还有一件事我想问你是否要提取名称不包含'a'的列表
  • 更改条件为:!x["name"].Contains("a")
猜你喜欢
  • 1970-01-01
  • 2022-01-05
  • 1970-01-01
  • 1970-01-01
  • 2021-09-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-02
相关资源
最近更新 更多