Search code examples
c#.netlinqgroup-byilist

How to group IList<T> using LINQ?


public static IList<string> GetAttribute_1(ModelContainer context, long productcatid)
{
    var query = from product in context.Products
                where product.ProductCategory_Id == productcatid
                select product.Attribute_1;

    return query.ToList();
}

how do i group by product.Attribute_1?


Solution

  • Grouping can be done by using the group by linq operator.

    The syntax would be something like:

    var query = from product in context.Products
                            where product.ProductCategory_Id == productcatid
                            group product by prodyct.Attribute_1 into g
                            select new { Attribute_1 = g.Key, Products = g }; 
    

    Here you can find Linq samples for grouping.

    But I suppose you want all the unqiue Attribute_1 properties returned from your function?

    You could then use the Distinct operator. That will fiter your list of Attribute_1 strings to contain only unique values.