简体   繁体   中英

Extract record from dictionary list where key and value does not contains given value list c#

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);

return record where list doesn't not contains key = 'address' and name= 'aa'

Update :- return record where name= 'aa'

Pretty simple with linq:

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

and if only one record is required back then use FirstOrDefault() :

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

Don't forget to add on top:

using System.Linq;

UDPATE:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM