在select语句中重用匿名变量[复制]

时间:2020-12-05 12:03:01

This question already has an answer here:

这个问题已经有了答案:

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.

在上面的lambda中,在计算eg的百分比(totresponcecount/Count)*100时,上面的语句中已经计算了Count。

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

那么如何访问Count值来写入Perc = (totresponcecount/Count)*100呢?

2 个解决方案

#1


4  

I would advise to use one more select statement to save this variable:

我建议再使用一个select语句来保存这个变量:

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();

#2


5  

I think in this case query syntax is nicer using the let keyword:

我认为在这种情况下查询语法会更好地使用let关键字:

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().

还要注意,您可以将谓词传递给Count方法,因此不需要(…).Count()。

#1


4  

I would advise to use one more select statement to save this variable:

我建议再使用一个select语句来保存这个变量:

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();

#2


5  

I think in this case query syntax is nicer using the let keyword:

我认为在这种情况下查询语法会更好地使用let关键字:

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().

还要注意,您可以将谓词传递给Count方法,因此不需要(…).Count()。