【问题标题】:linq join and countlinq 加入和计数
【发布时间】:2012-08-23 10:44:32
【问题描述】:

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

【问题讨论】:

    标签: c# asp.net linq


    【解决方案1】:
    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();
    

    【讨论】:

    • 您的回答假设每个客户始终至少有一笔交易。请参阅我的答案,了解不做此假设的方法。
    【解决方案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() };
    

    【讨论】:

      猜你喜欢
      • 2018-10-21
      • 2014-05-14
      • 1970-01-01
      • 2017-08-26
      • 1970-01-01
      • 2011-07-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多