linq加入和统计

时间:2012-08-23 10:44:33

标签: c# asp.net 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

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分: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() };