linq加入和统计

我是Linq的新手,想知道如何获取客户ID列表以及他们的交易计数

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 

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

无需加入您拥有Transaction对象的所有信息。

但是,如果您需要额外的客户信息(例如客户姓氏),您需要加入,在这种情况下,您可以执行以下操作;

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

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