LINQ加入和计数 [英] linq join and count

查看:153
本文介绍了LINQ加入和计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来的LINQ和想知道我怎么会去获取客户ID的列表,其交易的计数

 公共类交易
{
    公众诠释TRANSACTIONID {搞定;组;}
    公众诠释客户编号{搞定;组;}
}
公共类客户
{
    公众诠释ID {搞定;组;}
    公共字符串名称{;组;}
    公共字符串姓氏{搞定;组;}
}

我想我需要加入的客户交易,但也不太清楚我怎么会得到计数。

  VAR的查询=(从C在顾客
                    加入吨的交易上c.ID等于t.CustomerId


解决方案

  VAR的查询=交易
                .GroupBy(T => t.CustomerId)
                    。选择(T =>新建{ID = t.Key,TRANCOUNT = t.Count()})
                        .ToList();

没有必要加入你的交易对象上的所有信息。

您会,不过需要加入,如果你想额外的客户信息,如客户的姓氏,在这种情况下,你可以做以下;

  VAR的查询=(从C在顾客
                加入吨的交易上c.ID等于t.CustomerId
                C组由c.ID到GRP
                新选择
                {
                    ID = grp.Key,
                    姓= grp.First()。姓,
                    TRANCOUNT = grp.Count()
                })了ToList()。

I'm new to Linq and was wondering how I would go about obtaining a List of Customer Id, and a count of their transactions

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

I think I need to join customers with transactions but not too sure how I would get the count.

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

No need to join you have all the information on the Transaction object.

You would, however need to join if you wanted extra customer information such as customer surname, in which case you could do the following;

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

这篇关于LINQ加入和计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆