LINQ GroupBy Count

本小妞迷上赌 提交于 2020-01-04 09:14:08

问题


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)

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 ...


回答1:


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



回答2:


I'm thinking the query will look something like this

  EntityQuery<EmployeeProduct> query = from c in _employ.CountProduct()
                                         group c by new {c.UserId, c.ProductId, c.Name}
                                         into g
                                         select new {
                                            g.UserId,
                                            g.ProductId,
                                            g.Name,
                                            Count = g.Count()
                                         }


来源:https://stackoverflow.com/questions/8919100/linq-groupby-count

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!