我有一个类对象列表,其中一个类属性是包含杂项值的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”的物品。
List<string>
没有列名可供引用,我不知道该如何编写此表达式。