LINQ Group按计数 [英] LINQ GroupBy Count

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

问题描述

我有一个包含EmployeeID,ProductID和ProductName的表.该表称为EmployeeProduct,我想进行查询(将其绑定到DataGrid),这将使我得到如下结果:

I've got table which contains of EmployeeID, ProductID and ProductName. The table is called EmployeeProduct and I'd like to make query (which I'll bind to DataGrid) which will get me a result like this:

Employee ID| ProductID | Name | Count(ProductID)
   1       |     2     | XYZ  | 3
   1       |     5     | ZXY  | 2
   2       |     2     | XYZ  | 1

我试图通过此查询获取类似信息,但并没有得到结果... //更新-现在,我尝试通过这种方式进行操作,但仍然没有结果...//

I tried to get sth like this by this query, but it doesn't take a result... // UPDATED - Now I try to do this this way, but still have no result... //

(Home.xaml.cs)

(Home.xaml.cs)

public class ProductCount
{
    public int ProductNumber { get; set; }
    public int EmployeeNumber { get; set; }
    public int CountProducts { get; set; }
}

public IQueryable<ProductCount> CountProducts()
{
    var data = from b in _employ.EmployeeProduct
        group b by new { b.EmployeeID, b.ProductID } int z
        select new ProductCount { EmployeeNumber = z.Key.EmployeeID, ProductNumber = z.Key.ProductNumber, CountProducts = z.Count()};
    return data.AsQueryable();
}

以及以后的代码中,我想将此绑定到我的数据网格,但是不幸的是,它不会导致错误,但是如果我这样做:

and later in code I'd like to bind this to my datagrid, but unfortunately it don't causes error but if I do this:

dg.ItemsSource = CountProducts();

它什么也没显示...

it doens't show anything ...

推荐答案

以下是执行此操作的几种方法:

Here's a couple of way to do this:

var employeeProducts = new List<EmployeeProduct>();
employeeProducts.Add(new EmployeeProduct(1, 2, "XYZ"));
employeeProducts.Add(new EmployeeProduct(1, 5, "ZXY"));
employeeProducts.Add(new EmployeeProduct(2, 2, "XYZ"));

var way1 = employeeProducts.Select(
    ep => new ProductCount
                {
                    ProductNumber = ep.ProductID,
                    EmployeeNumber = ep.EmployeeID,
                    CountProducts = employeeProducts.Count(epc => epc.ProductID == ep.ProductID)
                });

var way2 = employeeProducts
    .GroupBy(ep => ep.ProductID)
    .SelectMany(epg => epg.Select(
        ep => new ProductCount
                    {
                        ProductNumber = ep.ProductID,
                        EmployeeNumber = ep.EmployeeID,
                        CountProducts = epg.Count()
                    }));

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

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