4

我是 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
4

2 回答 2

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();
于 2012-08-23T10:45:25.937 回答
2

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() };
于 2016-01-20T09:11:21.713 回答