如何在C# Linq中按两个字段对数据进行分组?

fzsnzjdm  于 2022-12-06  发布在  C#
关注(0)|答案(2)|浏览(224)

我有以下型号:

public class User
    {
       public long Id { get; set; }
       public string? Name { get; set; }
       public string? Surname { get; set; }
       public string? PhoneNumber { get; set; }
       public IEnumerable<Sale>? Sales { get; set; }
    }

    public class Product
    {
       [Key]
       public int Id { get; set; }
       public string Name { get; set; }
       public decimal Price { get; set; }
       public IEnumerable<Sale>? Sales { get; set; }
    }
    
    public class Sale
    {
       public int Id { get; set; }
       public User? User { get; set; }
       public List<SaleItem> SaleItems { get; set; }
       public DateTime CreatedDt { get; set; }
    }

    public class SaleItem
    {
        public int Id { get; set; }
        public Sale? Sale { get; set; }
        public Product? Product { get; set; }
        public int Count { get; set; }
    }

需要获得按客户和产品分组的计数和价格。
我试图用下面的方法解决这个问题:

var list = await context.SaleItems
    .Include(x => x.Product)
    .Include(x => x.Sale).ThenInclude(x => x.User)
    .Select(x => new
    {
        UserId = x.Sale.User.Id,
        UserName = x.Sale.User.Name,
        ProductId = x.Product.Id,
        ProductName = x.Product.Name,
        TotalCount = x.Count,
        TotalPrice = x.Product.Price * x.Count
    })
    .GroupBy(x => new { x.UserId, x.ProductId })
    .SelectMany(x => x)
    .ToListAsync();

但它不工作。谢谢!

vfhzx4xs

vfhzx4xs1#

SelectMany在这里是错误运算符您也可以删除Includes,因为不需要它们

var list = await context.SaleItems
    .Select(x => new
    {
        UserId = x.Sale.User.Id,
        UserName = x.Sale.User.Name,
        ProductId = x.Product.Id,
        ProductName = x.Product.Name,
        TotalCount = x.Count,
        TotalPrice = x.Product.Price * x.Count
    })
    .GroupBy(x => new { x.UserId, x.ProductId })
    .Select(g => new 
    {
        g.Key.UserId, 
        g.Key.ProductId,

        Count = g.Sum(x => x.TotalCount),
        TotalPrice = g.Sum(x => x.TotalPrice)
    })
    .ToListAsync();
qmb5sa22

qmb5sa222#

SelectMany()将返回列表的列表的查询扁平化。
使用.Select(x => x)而不是.SelectMany(x => x)
您可以查看Difference Between Select and SelectMany以获得更详细的说明。

相关问题