2017-06-22 113 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()