tags:

views:

59

answers:

3

Given the following table structure, how can I use a Linq query to return a list of Category names and the total count of products in that category?

Category
---------
ID
Name

Product
---------
ID 
IDCategory
Name

My ideal, return would be:

Clothes 156
Electronics 2149
Utensils 412

Etc.

EDIT: Thanks for the helpful suggestions, I now have this:

class Program
{
    static void Main(string[] args)
    {
        MyDatabaseEntities entities = new MyDatabaseEntities();

        var result = from c in entities.Categories
                        join p in entities.Products on c.ID equals p.IDCategory
                        group p by c.Name into g
                        select new
                        {
                            Name = g.Key,
                            Count = g.Count()
                        };

        Console.WriteLine(result.ToString());
        Console.ReadLine();
    }
}

How exactly can I output what is in the result? During debugging I can view the variables values and it has what I need I just don't know how to show it.

+3  A: 
from c in Category
join p in Product on c.ID equals p.IDCategory
group p by c.Name into g
select new
{
    Name = g.Key,
    Count = g.Count()
}

That will work in any flavor of LINQ, and groups by the Name, rather than the ID of category.

If you are using LINQ to Entities, this may be faster, and groups on ID rather than name:

from p in Product
group p by p.Category into g
select new
{
    Name = g.Key.Name,
    Count = g.Count()
}
John Gietzen
This query is fine. Note, however, that if duplicate c.Name values exist, then they will be grouped together in this query.
kbrimington
Yep, I was editing my answer.
John Gietzen
Hi John, I tried the first method and it works great, my only problem is I don't know how to extract the information from the var variable. How can I extract information from the returned result?
Serg
@Sergio: Use this for example: `foreach(var r in results) { Console.WriteLine("{0} {1}", r.Name, r.Count); }`
John Gietzen
A: 
public void Linq77()
{
    List<Product> products = GetProductList();

    var categoryCounts =
        from p in products
        group p by p.Category into g
        select new { Category = g.Key, ProductCount = g.Count() };

    ObjectDumper.Write(categoryCounts
}

See this link for specific LINQ examples.

j0rd4n
What datatype is categoryCounts? How would I extract the resuls from it?
Serg
It is an IEnumerable<T>. T in this case is an anonymous type because it is defined by the projected select statement (at compile time).
j0rd4n
Since it is IEnumerable<T>, you can iterate it via a foreach loop or another linq expression.
j0rd4n
+1  A: 

This query ensures that categories with duplicate names are not grouped together.

from p in context.Product
group p by p.Category into grp
select new
{
    CategoryName = grp.Key.Name,
    Count = grp.Count()
}
kbrimington