C# LINQ如何过滤包含指定值的列表属性类对象?
解决方法:用LINQ筛选包含特定值的List属性的类对象
没问题,我帮你搞定这个LINQ筛选的需求!先理清楚场景,咱们一步步来:
首先,假设你的目标类结构是这样的(对应你说的「某个类属性为List
public class Item { public string Name { get; set; } // 这个就是存储各类值的List属性,比如分类标签列表 public List<string> Categories { get; set; } }
然后咱们先模拟一组示例数据,方便测试:
// 你的类对象集合示例 var items = new List<Item> { new Item { Name = "Wrench", Categories = new List<string> { "Tool", "Hardware" } }, new Item { Name = "Drill", Categories = new List<string> { "Tool", "PowerTool" } }, new Item { Name = "Apple", Categories = new List<string> { "Fruit" } }, new Item { Name = "Hammer", Categories = new List<string> { "Hardware" } } };
接下来要实现的GetItemInfo方法,核心逻辑是用LINQ的Where结合Any方法——因为我们要检查每个Item的Categories列表是否包含目标值,Any正好用来判断集合中是否存在满足条件的元素。
完整的方法实现
public List<Item> GetItemInfo(string targetValue) { return items .Where(item => // 先判断List属性是否为null,避免空引用异常 item.Categories != null && // 检查列表中是否存在和目标值匹配的元素 item.Categories.Any(category => category == targetValue)) .ToList(); }
调用效果
当你调用GetItemInfo("Tool")时,就会精准返回Name为"Wrench"和"Drill"的两个Item对象,完全符合你的需求。
额外优化建议
- 如果需要忽略大小写的匹配(比如输入"tool"也能匹配到结果),可以把判断条件改成:
category.Equals(targetValue, StringComparison.OrdinalIgnoreCase) - 如果你的
Categories列表确定不会为null,可以去掉item.Categories != null &&这部分简化代码。
内容的提问来源于stack exchange,提问作者FactoryOptimizr
相关产品推荐
相关产品推荐

