ErocM ErocM - 2 months ago 6
C# Question

Can my two linq lines of code be combined?

I'm not sure how to do this since I'm only familiar with the basic form or Linq.

Here are my two sets of code:

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


Ultimately, I want to get my first query in order of Branch + Account Number distinctly.

Can they be combined or is what I have the only way to do this?

Thanks in advanced!

Answer

The quick and dirty solution is just to add the GroupBy chain to the end of the first query.

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

Or do the following by incorrupating the group by into the exist query syntax

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