将具有多个from的linq查询表达式转换为扩展方法语法

本文关键字:转换 表达式 查询表 扩展 语法 方法 查询 linq from | 更新日期: 2023-09-27 17:58:53

我在将此代码转换为扩展方法语法时遇到问题:

var query = from c in _context.Customers
                        from o in c.Orders
                        where o.DateSent == null
                        select new CustomerSummary
                        {
                            Id = c.Id,
                            Username = c.Username,
                            OutstandingOrderCount = c.Orders.Count
                        };

有什么想法吗?

将具有多个from的linq查询表达式转换为扩展方法语法

var query = _context.Customer
  .Where(c => c.Orders.Any(o => o.DateSent == null))
  .Select(c => new CustomerSummary
  {
    Id = c.Id,
    Username = c.Username,
    OutstandingOrderCount = c.Orders.Count(o => o.DateSent == null)
  };

试试这个:

        var query =
            _context.Customers.SelectMany(c => c.Orders, (c, o) => new {c, o}).Where(@t => o.DateSent == null)
                .Select(@t => new CustomerSummary
                                 {
                                     Id = c.Id,
                                     Username = c.Username,
                                     OutstandingOrderCount = c.Orders.Count
                                 });