Add item count to LINQ select

I have a problem that I canโ€™t wrap my head around.

I have a product list containing categories. I want to read all the categories and calculate how often they occur.

In another method, I want to take a categoryCount, divide it by the total number of tickets and multiply by 100 to get a percentage.

The problem is Count.

This is my request:

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 that I cannot use counter ++. Is there a workaround? The option of constructing a query to count each category is not an acceptable option. The list has 15,000 Listitems and is growing. In the end, I need to iterate over each category and call a query to count tickets that take only about 3 minutes. Therefore, the calculation of the catechism in one request is mandatory.

Any help is appreciated.

/ edit: for the sake of clarity: the counter + + as a counter was just a brain - I don't know why I tried this; this would lead to an index. I needed a way to calculate how often the "category" occurred in these records 15 thousand ..

+4
source share
1 answer

You can use GroupBy to execute Count inside the request 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() }); 
+4
source

All Articles