2017-06-22 112 views
0

我想獲得一組符合特定條件的記錄。 想象我有一個訂單列表,每一個嵌套的帳戶,有點像這樣: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 
    } 
}]; 

我想使用LINQ來得到一個基於帳戶ID的所有獨立的帳戶。 我想我也許可以這樣做:

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