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

4

我在将这段代码转换成扩展方法语法时遇到了一些麻烦:

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

有什么想法吗?

1
ReSharper可以自动转换方法链的格式,以防您不知道。 - Daniel Mann
1
所以可以访问http://www.linqpad.net。 - Marty Neal
1
你确定这个查询符合你的要求吗?我假设你只想要每个客户的单个记录,并计算出具有空SentDate的订单数量。 - NerdFury
问题的被接受答案是不正确的。请参见http://stackoverflow.com/q/14849965/15541以获取正确的建议。 - leppie
2个回答

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

1

试试这个:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接