[英]C# LINQ - Filtering by list-type property within a class
我有一个类对象列表,其中一个类属性是包含杂项值的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”的Items
myInfo.GetItemInfo("Power")
应仅返回名为“Drill”的Item
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();
您可以使用Linq Where
子句以及Any
扩展方法。
...
...
if (Attribute == null) return itemList;
return itemList.Where(item => item.Attributes.Any(x => x == Attribute)).ToList();
您可以使用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();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.