我可以在OneLiner中转换这两个LINQ语句(C#)

时间:2013-11-15 15:50:34

标签: c# linq

我有那些陈述检查我是否在网格中有所有答案。每一行都由ContextYID标识。

我想知道我是否可以将这些LinQ查询组合并将其直接转换为True / False语句。

int nbRow = Answers.Where(a => a.FieldId == result.Id && a.FieldYId == fieldYAxi.Id)
                   .Select(a => a.ContextYId)
                   .Distinct()
                   .Count();

int nbAnswer = Answers.Count(a =>
a.FieldId == result.Id &&
a.FieldXId == fieldXAxi.Id &&
a.FieldYId == fieldYAxi.Id);

if (nbAnswer != nbRow)
    return false;
else
    return true;

4 个答案:

答案 0 :(得分:4)

我认为这是一项改进,因为FieldIdFieldYID只需要进行一次比较,我将您的退货声明简化为一行。

var matchingAnswers = Answers.Where(a => a.FieldId == result.Id
                                      && a.FieldYId == fieldYAxi.Id).ToList();
int nbRow = matchingAnswers
                .Select(a => a.ContextYId)
                .Distinct()
                .Count();
int nbAnswer = matchingAnswers.Count(a => a.FieldXId == fieldXAxi.Id);
return nbAnswer == nbRow;

如果您愿意,可以通过合并最后几行来缩短这一点:

var matchingAnswers = Answers.Where(a => a.FieldId == result.Id
                                      && a.FieldYId == fieldYAxi.Id).ToList();
return matchingAnswers.Count(a => a.FieldXId == fieldXAxi.Id) ==
       matchingAnswers.Select(a => a.ContextYId).Distinct().Count();

答案 1 :(得分:3)

不等于工作吗?

return Answers.Where(a => a.FieldId == result.Id && a.FieldYId == fieldYAxi.Id)
               .Select(a => a.ContextYId)
               .Distinct()
               .Count()
               .Equals(Answers.Count(a =>
                       a.FieldId == result.Id &&
                       a.FieldXId == fieldXAxi.Id &&
                       a.FieldYId == fieldYAxi.Id));

答案 2 :(得分:0)

我认为这应该有效。你想要这样做有什么特别的原因吗?

return Answers.Where(a => a.FieldId == result.Id && a.FieldYId == fieldYAxi.Id)
              .Select(a => a.ContextYId)
              .Distinct()
              .Count()
    == Answers.Count(a => a.FieldId  == result.Id 
                       && a.FieldXId == fieldXAxi.Id 
                       && a.FieldYId == fieldYAxi.Id)

答案 3 :(得分:0)

认为这在功能上等同于正在做的事情(但我确实想知道你为多次满足nbAnswer的重复ContextYIds做了什么):

var distinctContextYIds = new HashSet<int>();

return 0 == Answers.Where(a => a.FieldId == result.Id && a.FieldYId == fieldYAxi.Id)
    .Aggregate(0, (tally, answer) =>
    {
        if (distinctContextYIds.Add(answer.ContextYId))
            tally += 1;

        if (answer.FieldXId == fieldXAxi.Id)
            tally -= 1;

        return tally;
    });