add item count to LINQ select

c#, c#-4.0, linq, sharepoint

Solution

You can use `GroupBy` to perform the `Count` within the query itself:

return Tickets
           .Where(t =>  t.Kategorie != Kategorie.Invalid && t.Kategorie != Kategorie.None && t.Kategorie != null)
           .GroupBy(t => t.Kategorie.ToString())
           .Select(g => new KategorieVM() { _name = g.Key, _val = g.Count() });

Problem

I have a problem I cant wrap my head around. I have a Sharepoint List of Items, which have Categories. I want to read all Categories and count how often, they occur. In another method, I want to take the categoryCount, divide it by the total number of tickets and multiply by 100 to get a percentage. The problem is the Count. This is my query so far: ``` public IEnumerable<KategorieVM> GetAllCategories() { int counter = 0; var result = (from t in Tickets where t.Kategorie != Kategorie.Invalid && t.Kategorie != Kategorie.None && t.Kategorie != null select new KategorieVM() { _name = t.Kategorie.ToString(), _val = counter++ }); return result; } ``` the problem is, I can't use counter++. Is there a clean workaround? The option to build a query for the purpose of counting each category is not a valid option. The list has 15000 Listitems and growing. In the end I need to iterate through every category and call the query to count the tickets which just takes about 3 minutes. So counting the cateogry in one query is mandatory. Any help is highly appreciated. /edit: for the sake of clearity: the counter++ as count was just a brainfart - I dont know why I tried it; this would have resulted in an index. I needed a way to count how often the 'category' occured in those 15k entries.

Original source