使用linq和lambda查询查找具有3个或3个以上产品数据的类别

本文关键字:3个 数据 查询 lambda 查找 使用 linq | 更新日期: 2023-09-27 18:05:53

我正在查找有3个或更多产品的类别id或类别名称。

List在class Category中,但是我必须在main中写出结果。

public static IEnumerable<Product> GetProducts( )
{
    List<Product> products = new List<Product>( );
    products.Add( new Product { Name = "Milk",           Price = 90,  CategoryID = 4, ID = 1 } );
    products.Add( new Product { Name = "Cheese",         Price = 130, CategoryID = 4, ID = 2 } );
    products.Add( new Product { Name = "Butter",         Price = 110, CategoryID = 4, ID = 3 } );
    products.Add( new Product { Name = "Apple juice",    Price = 230, CategoryID = 1, ID = 4 } );
    products.Add( new Product { Name = "Grape juice",    Price = 240, CategoryID = 1, ID = 5 } );
    products.Add( new Product { Name = "Beetroot juice", Price = 300, CategoryID = 1, ID = 6 } );
    products.Add( new Product { Name = "Carrot juice",   Price = 190, CategoryID = 1, ID = 7 } );
    products.Add( new Product { Name = "Ginger ale",     Price = 990, CategoryID = 1, ID = 8 } );
    products.Add( new Product { Name = "Oregano",        Price = 500, CategoryID = 2, ID = 9 } );
    products.Add( new Product { Name = "Salt",           Price = 550, CategoryID = 2, ID = 10 } );
    products.Add( new Product { Name = "Pepper",         Price = 490, CategoryID = 2, ID = 11 } );
    products.Add( new Product { Name = "Carrots",        Price = 300, CategoryID = 3, ID = 12 } );
    products.Add( new Product { Name = "Spinach",        Price = 250, CategoryID = 3, ID = 13 } );
    products.Add( new Product { Name = "Onion",          Price = 200, CategoryID = 3, ID = 14 } );
    products.Add( new Product { Name = "Garlic",         Price = 150, CategoryID = 3, ID = 15 } );
    products.Add( new Product { Name = "Tomatoes",       Price = 100, CategoryID = 3, ID = 16 } );
    return products;
}

使用linq和lambda查询查找具有3个或3个以上产品数据的类别

var products = GetProducts();
IEnumerable<int> categoriesWithThreeOrMoreProducts =
            from p in products
            group p by p.CategoryID into grps
            where grps.Count() >= 3
            select grps.Key;

取产品列表,按类别对产品进行分组(因此grps成为映射,将每个类别id映射到该类别中的产品),选择包含三个或更多元素的组,然后返回这些组的键(类别id)。

或者,稍微不那么LINQ-ish:

IEnumerable<int> categoriesWithThreeOrMoreProducts =
                   products.ToLookup(p => p.CategoryID)
                           .Where(g => g.Count() >= 3)
                           .Select(g => g.Key);

我想你可以这样做:

    var p1 = GetProducts();  
    var res =p1
            .GroupBy(p => p.CategoryID)
            .Where(g => g.Count() >= 3)
            .SelectMany(g => g.CategoryName);

如果你需要产品的名称,那么你需要这样做,但如果只有CategoryID -> Select(g => g. key)