C#LINQ - 按类中的list-type属性进行过滤

时间:2018-02-16 19:36:29

标签: c# linq

我有一个类对象列表,其中一个类属性是包含其他值的List<string>。我需要编写一个LINQ查询来返回包含List<string>属性中某个值的类对象。

这是一个示例类......

public class Item
{
    public string Name { get; set; }
    public int ID { get; set; }
    public List<string> Attributes { get; set; }
}

这是一些基于指定属性值过滤的数据和方法的示例:

public class Info
{
    public List<Item> GetItemInfo(string Attribute = null)
    {
        List<Item> itemList = new List<Item>
        {
            new Item { Name = "Wrench",  ID = 0, Attributes = new List<string> { "Tool"  } },
            new Item { Name = "Pear",    ID = 1, Attributes = new List<string> { "Fruit" } },
            new Item { Name = "Apple",   ID = 2, Attributes = new List<string> { "Fruit" } },
            new Item { Name = "Drill",   ID = 3, Attributes = new List<string> { "Tool",   "Power"  } },
            new Item { Name = "Bear",    ID = 4, Attributes = new List<string> { "Animal", "Mammal" } },
            new Item { Name = "Shark",   ID = 5, Attributes = new List<string> { "Animal", "Fish"   } }
        };

        // If no Attribute specified, return the entire item list
        if (Attribute == null) return itemList;

        // Otherwise, filter by the Attribute specified
        else return  ?????
    }
}

调用GetItemInfo方法会返回此信息:

myInfo.GetItemInfo("Tool")应该返回名为“Wrench”和“Drill”的项目

myInfo.GetItemInfo("Power")应仅返回名称为“Drill”的项目

myInfo.GetItemInfo("Fruit")应该返回名为“Pear”和“Apple”的项目

使用子查询编写LINQ表达式非常容易。但是,在这种情况下,因为List<string>没有要引用的列名,所以我在努力编写这个表达式。

3 个答案:

答案 0 :(得分:4)

// Otherwise, filter by the Attribute specified
else return itemList
    .Where(x => x.Attributes.Contains(Attribute))
    .ToList();

答案 1 :(得分:3)

您可以使用Linq Where子句和Any扩展名方法。

...
...
if (Attribute == null) return itemList;    
return itemList.Where(item => item.Attributes.Any(x => x == Attribute)).ToList();

答案 2 :(得分:2)

您可以使用LINQ Where子句吗?

public class Info
{
    public List<Item> GetItemInfo(string Attribute = null)
    {
        List<Item> itemList = new List<Item>
        {
            new Item { Name = "Wrench",  ID = 0, Attributes = new List<string> { "Tool"  } },
            new Item { Name = "Pear",    ID = 1, Attributes = new List<string> { "Fruit" } },
            new Item { Name = "Apple",   ID = 2, Attributes = new List<string> { "Fruit" } },
            new Item { Name = "Drill",   ID = 3, Attributes = new List<string> { "Tool",   "Power"  } },
            new Item { Name = "Bear",    ID = 4, Attributes = new List<string> { "Animal", "Mammal" } },
            new Item { Name = "Shark",   ID = 5, Attributes = new List<string> { "Animal", "Fish"   } }
        };

        // If no Attribute specified, return the entire item list
        if (Attribute == null) return itemList;

        // Otherwise, filter by the Attribute specified
        else return itemList.Where(i => i.Attributes.Contains(Attribute)).ToList();
    }
}