C# LINQ - 按类中的列表类型属性过滤

标签 c# linq

我有一个类对象列表,其中一个类属性是 List<string>包含杂项值。我需要编写一个 LINQ 查询来返回在 List<string> 中包含特定值的类对象属性(property)。

这是一个示例类...

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”的 Items

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

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

很容易编写带有子查询的 LINQ 表达式。然而,在这种情况下,因为 List<string>没有要引用的列名,我正在为如何编写此表达式而苦苦挣扎。

最佳答案

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

关于C# LINQ - 按类中的列表类型属性过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48833692/

相关文章:

c# - Linq/Enumerable Any Vs 包含

c# - system.linq groupby 多个元素

c# - 如何在任务内关闭 WPF 窗口

c# - 影响如何在 EF 6 代码优先中从数据库创建实体类

c# - 为什么我的 EF Code First 预生成 View 无效?

c# - 如何在单例类中使用 transient 记录器,简单注入(inject)器

c# - 在 ListView 中对项目进行分组 - Windows 应用商店应用

c# - 如何在列表 <> 中查找重复项?

c# - 所有 LINQ 查询表达式关键字的列表?

c# - LINQ 的强制转换问题