2017-06-22 9 views
0

特定の条件に一致するレコードのセットを取得しようとしています。私はアカウントIDに基づいて、すべての個別のアカウントを取得するためにLINQを使用したいLINQ GroupByとDistinct

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

: は、ネストされたアカウントを持つ各、私が注文のリストを持っている。このようなビットを想像してみてください。 私はのような何かを行うことができるかもしれないと思った:

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

それが動作するように表示されません。 誰かが私を助けることができますか?

答えて

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

、より良い、AccountクラスにIEquatable<T>を実装:

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; 
} 

その後、シンプルかつ効果的な:

results.Select(m => m.Account).Distinct(); 
0
results.Select(m => m.Account).GroupBy(m => m.AccountNumber) 
          .Select(g => g.First()).ToList()