ErocM
ErocM

Reputation: 4662

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?

Upvotes: 0

Views: 75

Answers (2)

M B
M B

Reputation: 2326

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

Upvotes: 2

juharr
juharr

Reputation: 32266

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

Upvotes: 3

Related Questions