C# LINQ - 在类的列表属性中进行过滤

3

我有一个类对象列表,其中一个类属性是包含杂项值的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个回答

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

3
您可以使用 Linq 的 Where 子句和 Any 扩展方法。
...
...
if (Attribute == null) return itemList;    
return itemList.Where(item => item.Attributes.Any(x => x == Attribute)).ToList();

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接