0

我正在尝试将循环转换为 linq 表达式。但它似乎不能像我这样做的那样工作:

var customer = GetCustomerFromDatabase(id);
ICollection<Order> customerOrders = null;
if (customer == null)
{
    LogAndThrowCustomerNotFound(id);
}
else
{
    customerOrders = customer.Orders;
}

customer.YearToDateSales = 0.0;
customer.CurrentSales = 0.0;
DateTime today = DateTime.Now;

if (customerOrders != null)
    foreach (var order in customerOrders)
    {
        if (order.SubmittedDate != null 
            && order.SubmittedDate.Value.Year.CompareTo(today.Year) == 0)
        {
            customer.YearToDateSales += (double)order.OrderTotal;
        }

        if (order.SubmittedDate != null 
            && (order.SubmittedDate.Value.Month.CompareTo(today.Month) == 0 
            && order.SubmittedDate.Value.Year.CompareTo(today.Year) == 0))
        {
            customer.CurrentSales += (double)order.OrderTotal;
        }
    }

所以我想出了这个表达式来获得与当年匹配的客户订单......它不起作用。在他的表达顺序是空的,今天是矛盾的。我今天创建 DateTime = DateTime.Now; 在表达式的参数中我得到不同的错误......

IEnumerable<Order> cOrders = customerOrders
   .Where((ICollection<Order> order , today) =>
           order.SubmittedDate.Value.Month == today.Month);
4

2 回答 2

2

如果您只是不尝试传递today到 lambda,它会更简单,无论如何它都会被关闭到表达式中;

customer.YearToDateSales = customerOrders
    .Where(x => x.SubmittedDate != null && 
                x.SubmittedDate.Value.Year == today.Year)
    .Sum(x => x.OrderTotal);

customer.CurrentSales = customerOrders
    .Where(x => x.SubmittedDate != null && 
                x.SubmittedDate.Value.Month == today.Month &&
                x.SubmittedDate.Value.Year  == today.Year)
    .Sum(x => x.OrderTotal);
于 2013-05-21T17:49:10.247 回答
0

如果没有错误,很难准确判断出了什么问题,但您可能需要检查SubmittedDate原始版本中的 null 等:

IEnumerable<Order> cOrders = customerOrders
      .Where((ICollection<Order> order , today) => 
         order.SubmittedDate.HasValue && 
         order.SubmittedDate.Value.Month == today.Month);
于 2013-05-21T17:30:32.990 回答