gpt4 book ai didi

c# - LINQ GroupBy 计数

转载 作者:行者123 更新时间:2023-11-30 22:32:02 25 4
gpt4 key购买 nike

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

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

我试图通过这个查询得到这样的东西,但它没有结果......//已更新 - 现在我尝试这样做,但仍然没有结果...//

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

稍后在代码中我想将其绑定(bind)到我的数据网格,但不幸的是它不会导致错误,但如果我这样做:

dg.ItemsSource = CountProducts();

它没有显示任何东西......

最佳答案

这里有几种方法可以做到这一点:

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

关于c# - LINQ GroupBy 计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8919100/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com