我有一个类对象列表,其中一个类属性是 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/