我的两个linq代码行可以合并吗?

时间:2016-09-12 19:06:40

标签: c# linq

我不知道怎么做,因为我只熟悉基本形式或Linq。

以下是我的两组代码:

      var qry = from x in CustomersChecks.CustomersChecksList
        where x.RoutingNumber == routingnumber &&
              x.BankAccountNumber == bankAccountNumber &&
          x.Branch > 0 &&
          x.AccountNumber > 0
          orderby x.Name
        select x;

  var qry2 = qry.GroupBy(x => new { x.Branch, x.AccountNumber}).Select(x => x.First()).ToList();

最终,我想明确地按分行+帐号顺序查询我的第一个查询。

他们可以合并,还是我唯一的方法呢?

先谢谢!

2 个答案:

答案 0 :(得分:3)

快速而肮脏的解决方案只是将GroupBy链添加到第一个查询的末尾。

var qry = (from x in CustomersChecks.CustomersChecksList
          where x.RoutingNumber == routingnumber &&
          x.BankAccountNumber == bankAccountNumber &&
          x.Branch > 0 &&
          x.AccountNumber > 0
          orderby x.Name
          select x).GroupBy(x => new { x.Branch, x.AccountNumber})
                   .Select(x => x.First())
                   .ToList();

或者通过将组破坏为现有查询语法

来执行以下操作
var qry = (from x in CustomersChecks.CustomersChecksList
          where x.RoutingNumber == routingnumber &&
          x.BankAccountNumber == bankAccountNumber &&
          x.Branch > 0 &&
          x.AccountNumber > 0
          orderby x.Name
          group x by new { x.Branch, x.AccountNumber} into grp
          select grp.First()).ToList();

答案 1 :(得分:2)

<?php

namespace SocialWall\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;


class CommentType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('content', TextareaType::class);
    }

    public function getName()
    {
        return 'comment';
    }
}