如何使用外部对象编写Linq表达式

本文关键字:Linq 表达式 对象 何使用 外部 | 更新日期: 2023-09-27 18:14:35

我正在尝试将循环转换为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. now;在表达式的parm中,我得到了不同的错误…

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

如何使用外部对象编写Linq表达式

如果您不尝试将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);

如果没有错误,很难确切地告诉什么是错的,但您可能需要像原始版本一样检查SubmittedDate上的null:

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