过滤字典逻辑问题列表

时间:2018-10-17 17:18:07

标签: c#

在我的List<Dictionary<string,string>> listOfAnimal中,我需要过滤出与名称Ant相同的记录。

字典由以下元素组成。

[
{
 "id":"5",
 "name": "Ant",
 "age":"6"
},
{
 "id":"52",
 "name": "Elephant",
 "age":"1"
},
{
 "id":"15",
 "name": "Ant",
 "age":"6"
},
{
 "id":"9",
 "name": "Ape",
 "age":"16"
}


]

因此,基本上,我需要过滤掉List<Dictionary<string,string>>,其中动物的nameAnt。我的方法如下:

var filtered= listOfAnimal.Values.Where(x=> x.Equals("Ant")).ToList();

上面没有提供字典中的其他元素,而是仅匹配名称。

有人可以在这里帮我吗

4 个答案:

答案 0 :(得分:1)

我不明白为什么要为此工作定义词典列表。您不需要该工作的字典,而且如果您使用字典,则密钥无论如何都必须是唯一的(ID比密钥的名称要好)。 如果您为动物编写类

public class Animal
{
    public int Id { get; set; }
    public string Name { get; set; }
    public uint age { get; set; }
}

并将其实例放入列表/可枚举

var filtered = raw.Where(animal=>animal.Name == "Ant");

只得到蚂蚁。

答案 1 :(得分:1)

并不是真的100%清楚您的情况,但请尝试一下。

var ants = listOfAnimal.SelectMany(d => d).Where(d => d.Value.Equals("Ant", StringComparison.OrdinalIgnoreCase));

答案 2 :(得分:1)

改为使用此:

var filtered = listOfAnimal
    .Where(x => x.TryGetValue("name", out var name) && name == "Ant")
    .ToList();

答案 3 :(得分:1)

您有一个词典列表,并且想要过滤(排除)键为"name"且值为"Ant"的词典。您可以按照以下步骤进行操作:

var filteredList = listOfAnimal
    .Where(d =>
           {
               string name;
               if (!d.TryGetValue("name", out name))
                   // Include the dictionary if it completely lacks a "name" entry.
                   return true;
               // Include the dictionary if the "name" entry is something other than "Ant".
               return name != "Ant";
           })
    .ToList();

如果您确实想过滤出没有具有值为"name"的键"Ant"的字典(您的问题有点模棱两可),您可以按照以下步骤操作:

var filteredList = listOfAnimal
    .Where(d =>
           {
               string name;
               if (!d.TryGetValue("name", out name))
                   // Exclude the dictionary if it completely lacks a "name" entry.
                   return false;
               // Include the dictionary if the "name" entry equals "Ant".
               return name == "Ant";
           })
    .ToList();

在您当前的代码中,您似乎正在尝试从单个字典中筛选键/值对,而不是从List<Dictionary<string,string>>中筛选整个字典。

提琴here

相关问题