Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reuse anonymous variable within select statement [duplicate]

Tags:

c#

.net

linq

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 above lambda, while calculating percentage for eg I want to write (totresponcecount/Count)*100 where Count is already calculated in above statement.

So how can I access Count value to write Perc = (totresponcecount/Count)*100?

like image 241
user3815413 Avatar asked Feb 11 '18 07:02

user3815413


2 Answers

I think in this case query syntax is nicer using 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 notice that you can pass a predicate to the Count method so no need for Where(...).Count().

like image 97
Gilad Green Avatar answered Oct 16 '22 11:10

Gilad Green


I would advise to use one more select statement to save 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();
like image 4
Maksim Simkin Avatar answered Oct 16 '22 09:10

Maksim Simkin