tags:

views:

150

answers:

2

Hi all, I have a table:

Id  Catg
1   cat01
2   cat01
3   cat01
1   cat02
2   cat02

now I want to detect number of occurance of catg01 and catg02,like in this ex, catg01 is 3 times and catg02 is 2 times,I want to count that through LINQ/ simple db query. Pls note: cant use Where clause and hardcode Catg01/catg 02,as there can n number of category.Is it possible to detect? if yes then pls help.

+5  A: 
Select Catg, Count(*) From TableName Group By CatG

For the LINQ Version. Imagine a Class

    class Table
    {
        public int ID { get; set; }
        public string CatG { get; set; }
    }

Then if you had a list of that class, you could query it as follows

List<Table> y = new List<Table>();

y.Add(new Table() { ID = 1, CatG = "a" });
y.Add(new Table() { ID = 2, CatG = "a" });
y.Add(new Table() { ID = 3, CatG = "a" });
y.Add(new Table() { ID = 4, CatG = "b" });
y.Add(new Table() { ID = 5, CatG = "b" });


var query = y.GroupBy(table => table.CatG);

// Iterate over each IGrouping in the collection.
foreach (var item in query)
{
    Console.WriteLine("CatG: {0} Number of Items: {1}", item.Key, item.Count());
}
Eoin Campbell
Thanks,it worked.can u pls help me with LINQ
Wondering
sure... will edit the post.
Eoin Campbell
+5  A: 
SELECT Catg, COUNT(*)
FROM myTable GROUP BY Catg
Alnitak