Home > Blockchain >  To divide a list of products by category usinq LINQ without foreach
To divide a list of products by category usinq LINQ without foreach

Time:07-22

How to return values in method without foreach? I mean i can easily to divide this in foreach loops, but i need to get the answer in this format IEnumerable<(string category, IEnumerable<string> productsName)>. What can i do?

public static IEnumerable<(string category, IEnumerable<string> productsName)> GroupByCategory()
{
    List<Product> products = Products.ProductList;

    var orderGroups = products.Where(p => p.ProductId <= 20).GroupBy(p => p.Category,
        (Key, g) => new { Category = Key, Products = g });

    foreach (var i in orderGroups)
    {
        Console.WriteLine($"Category={i.Category}:");
        foreach (var p in i.Products)
        {
            var s = $"ProductID={p.ProductId},
                    Product Name={p.ProductName},
                    UnitPrice={p.UnitPrice},
                    UnitsInStock={p.UnitsInStock}";

            Console.WriteLine(s);
        }
    }
}

CodePudding user response:

Something like this would probably work for you. Specifically the select and nested select statements.

public IEnumerable<(string category, IEnumerable<string> productsName)> GroupByCategory()
{
    List<Product> products = Products.ProductList;

    return products.Where(p => p.ProductId <= 20)
                   .GroupBy(p => p.Category)
                   .Select(g => (g.Key, g.Select(p => p.ProductName)));
}

Personally I would create a model to better encapsulate the result, something like CategoryGroup. You could then build a constructor for it which takes IGrouping<string, Product> as an argument to clean up the .Select even further, but that's just preference!

  • Related