Reusing an anonymous variable inside a select statement

db.opt.Select(z => new { z.QuestionTitle, Count = z.Responces.Where(x => x.Responseval == Constants.options.Agree).Count(), Perc = (totresponcecount/Count)*100 }).ToList(); 

In the lambda above, when calculating the percentage, for example, I want to write (totresponcecount/Count)*100 , where Count already calculated in the previous expression.

So, how can I access the Count value for writing Perc = (totresponcecount/Count)*100 ?

+5
source share
2 answers

I would suggest using another select statement to store this variable:

 db .opt .Select(z => new { z.QuestionTitle, Count = z.Responces.Where(x => x.Responseval == Constants.options.Agree).Count() }) .Select(z => new { z.QuestionTitle, z.Count, Perc = (totresponcecount / z.Count) * 100 }) .ToList(); 
+4
source

I think in this case the query syntax is better with the let keyword:

 var result = from z in db.opt let count = z.Responces.Count(x => x.Responseval == Constants.options.Agree) select new { z.QuestionTitle, count , Perc = (totresponcecount/count) * 100 }; 

Also note that you can pass the predicate to the Count method, so there is no need for Where(...).Count() .

+5
source

Source: https://habr.com/ru/post/1275292/


All Articles