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
  • 12,148
  • 20
  • 96
  • 242

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,170
  • 3
  • 32
  • 70
0
results.Select(m => m.Account).GroupBy(m => m.AccountNumber)
                          .Select(g => g.First()).ToList()
Patrick Hofman
  • 148,824
  • 21
  • 237
  • 306
A.B.
  • 2,043
  • 3
  • 21
  • 36