2012-08-23 41 views
4

我是新來的LINQ,並想知道我怎麼會去獲取客戶ID的列表,以及它們事務的計數LINQ加入和計數

public class Transaction 
{ 
    public int TransactionId {get; set;} 
    public int CustomerId {get; set;} 
} 


public class Customer 
{ 
    public int ID {get; set;} 
    public string Name {get; set;} 
    public string Surname {get; set;} 
} 

我想我需要加入的客戶交易但不太確定我會如何得到伯爵。

var query = (from c in customers 
        join t in transactions on c.ID equals t.CustomerId 

回答

3
var query = transactions 
       .GroupBy(t => t.CustomerId) 
        .Select (t => new { Id = t.Key, TranCount = t.Count() }) 
         .ToList(); 

無需加入你的交易對象上的所有信息。

如果您想要額外的客戶信息,例如客戶姓名,您可能需要加入,在這種情況下,您可以執行以下操作;

var query = (from c in customers 
       join t in transactions on c.ID equals t.CustomerId 
       group c by c.ID into grp 
       select new 
       { 
        Id = grp.Key, 
        Surname = grp.First().Surname, 
        TranCount = grp.Count() 
       }).ToList(); 
+0

你的回答假設總是有每個客戶至少一個事務。請參閱我的回答,找出一種不做此假設的方法。 –

1

saj的答案只適用於每個客戶都有交易的情況。相反,它會更好地使用一組連接開始Customer,並計算結果:

var query = from customer in customers 
      join transaction in transactions 
       on customer.Id equals transaction.CustomerId 
       into customerTransactions 
      select new { customer.Id, Count = customerTransactions.Count() };