You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 08:35:13