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

如何使用LINQ筛选包含用户选中分类的产品对象

解决方案

首先注意一个细节:你的userSelectedCategories是List<string>,但Category.CategoryID是int类型,直接对比会有类型不匹配问题,先把选中分类转换为int集合更高效。另外需要先把所有产品放到一个集合里,才能进行LINQ查询。

完整实现代码

修改你的Main方法,添加产品集合并执行筛选:

static void Main(string[] args)
{
    List<string> userSelectedCategories = new List<string> { "1", "3" };
    // 转换为int集合,避免重复转换
    var selectedCategoryIds = userSelectedCategories.Select(int.Parse).ToList();

    // 初始化产品集合
    List<Product> products = new List<Product>
    {
        new Product
        {
            ID = 1,
            Categories = new List<Category>
            {
                new Category { CategoryID = 1, Name = "Blue" },
                new Category { CategoryID = 2, Name = "Yellow" },
                new Category { CategoryID = 3, Name = "Green" },
                new Category { CategoryID = 4, Name = "Purple" }
            }
        },
        new Product
        {
            ID = 2,
            Categories = new List<Category>
            {
                new Category { CategoryID = 1, Name = "Blue" },
                new Category { CategoryID = 2, Name = "Yellow" }
            }
        },
        new Product
        {
            ID = 3,
            Categories = new List<Category>
            {
                new Category { CategoryID = 2, Name = "Yellow" }
            }
        }
    };

    // 方法语法写法
    var filteredProducts = products.Where(p => 
        p.Categories.Any(c => selectedCategoryIds.Contains(c.CategoryID))
    ).ToList();

    // 或者查询语法写法
    // var filteredProducts = (from p in products
    //                         where p.Categories.Any(c => selectedCategoryIds.Contains(c.CategoryID))
    //                         select p).ToList();

    // 输出结果验证
    foreach (var product in filteredProducts)
    {
        Console.WriteLine($"产品ID: {product.ID}");
    }
}

逻辑说明

  1. 类型转换:先把字符串类型的选中分类ID转为int集合,避免在LINQ查询中重复执行类型转换,提升性能。
  2. 筛选逻辑:使用Where过滤产品,通过Any判断当前产品的分类列表中,是否存在至少一个分类ID在选中集合里。
  3. 运行后会输出ID为1和2的产品,符合需求。

内容的提问来源于stack exchange,提问作者user2884789

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 17:13:27