【问题标题】:How to group data by two fields in C# Linq?如何在 C# Linq 中按两个字段对数据进行分组?
【发布时间】:2022-07-21 16:12:10
【问题描述】:

我有以下型号:

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

但它不起作用。 谢谢!

【问题讨论】:

  • “但它不起作用” - 如何它不起作用?您是否收到运行时错误?编译错误?出乎意料的结果?
  • 你为什么打电话给.SelectMany( x =&gt; x )?这违背了GroupBy 的观点。
  • 还有EF,指定哪个版本。

标签: c# linq


【解决方案1】:

SelectMany() 将返回列表列表的查询展平。

使用.Select(x =&gt; x) 而不是.SelectMany(x =&gt; x)

您可以查看Difference Between Select and SelectMany以获得更详细的说明。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-22
    • 1970-01-01
    • 2022-10-04
    相关资源
    最近更新 更多