1

I am trying to get a set of records that match certain criteria. Imagine I have a list of orders, each with a nested account, a bit like this:

var orders = [{
    account: {
        id: 1
    }
}, {
    account: {
        id: 1
    }
}, {
    account: {
        id: 2
    }
}, {
    account: {
        id: 2
    }
}, {
    account: {
        id: 1
    }
}, {
    account: {
        id: 4
    }
}, {
    account: {
        id: 3
    }
}];

I would like to use LINQ to get all the distinct accounts based on the account id. I thought I might be able to do something like:

var accounts = results.Select(m => m.Account).GroupBy(m => m.AccountNumber).Distinct();

but that doesn't appear to work. Can someone help me out?

r3plica
  • 13,017
  • 23
  • 128
  • 290

2 Answers2

5
var accounts = results
              .Select(m => m.Account)
              .GroupBy(m => m.AccountNumber)
              .Select(x => x.First());

and better, implement IEquatable<T> in Account class:

class Account : IEquatable<Account> 
{
    public int AccountNumber { get; set; }

    // more members....

    public bool Equals(Account another) => this.AccountNumber == another.AccountNumber;
    public override int GetHashCode() => this.AccountNumber;
}

then simple and effective:

results.Select(m => m.Account).Distinct();
dovid
  • 6,354
  • 3
  • 33
  • 73
0
results.Select(m => m.Account).GroupBy(m => m.AccountNumber)
                          .Select(g => g.First()).ToList()
Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
A.B.
  • 2,374
  • 3
  • 24
  • 40