【问题标题】:filter items from list of dictionary in c# based on matching key and values根据匹配的键和值从 C# 中的字典列表中过滤项目
【发布时间】:2020-06-10 03:33:43
【问题描述】:

我有字典列表:-

List<Dictionary<string, string>> list = 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");
list.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");
list.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");
list.Add(dict3);

在这个列表中我想找出那些地址包含'aa'的记录

【问题讨论】:

  • 那么您是否特别尝试过使用Linq 或标准循环?你有什么问题?
  • 你可以喜欢 list.Where(d => d.Values.Any(v => v.Contains("aa")));

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


【解决方案1】:

您可以使用WhereAny 方法来实现

var result = list.Where(d => d.Values.Any(v => v.Contains("aa")));

它会返回两个 Dictionary&lt;string, string&gt; 实例,其中包含带有 aa 的值。

如果您需要地址键的过滤列表并且值包含aa,则下面的代码将为您返回带有此类键的字典

var result = list.Where(d => d.ContainsKey("address") && d["address"].Contains("aa"));

此代码返回整个列表的键/值对的扁平序列

var result = list.SelectMany(l => l).Where(kv => kv.Key == "address" && kv.Value.Contains("aa"));

要执行不区分大小写的搜索(如 cmets 中所述),应将 StringComparison.OrdinalIgnoreCase 添加到 Contains 方法

var result = list.SelectMany(l => l).Where(kv =>
    kv.Key == "address" && kv.Value.Contains("Aa", StringComparison.OrdinalIgnoreCase));

【讨论】:

  • 我需要一个过滤列表,其中键是地址,值包含'aa'
  • 列出自身或其中的字典?
  • @shahbazusmani 我已经根据您的需要更新了我的答案(只是包含“aa”的地址列表)
  • @PavelAnikhouski 您更新后的答案对我有用,但如果我像“Aa”一样搜索,它不会返回任何记录
  • @shahbazusmani 你应该将StringComparison.OrdinalIgnoreCase 添加到Contains 方法,我已经更新了答案
【解决方案2】:

这将为您提供地址包含“aa”的字典列表

list.Where(x => x["address"].Contains("aa"));

忽略大小写敏感

list.Where(x => x["address"].ToLower().Contains("aa"));

这将为您提供一个扁平的记录列表,其中仅包含一对键、值,其中键是“地址”,值包含“aa”

list.Where(x => x["address"].Contains("aa")).SelectMany(y=>y.Where(item=>item.Key=="address"));

【讨论】:

  • 如果字典中有address键则抛出异常
  • @PavelAnikhouski 这是在所有记录中都有地址的基本假设。除此之外,如您所知,它很容易处理。在这里,我们正在讨论检索该记录的方法。顺便说一句,谢谢你,很好。
  • 第一个为我工作,我需要所有列表,其中键是地址,值包含'aa',谢谢@MohammadNikrvesh
  • 当我输入'Aa'时它没有返回记录,如何管理区分大小写的搜索
  • @shahbazusmani 你需要在 Contains(...) 之前使用 .ToLower() 方法我已经更新了我的答案,你可以在那里找到。
猜你喜欢
  • 2020-02-06
  • 1970-01-01
  • 1970-01-01
  • 2015-05-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多