2013-05-21 21 views
0

我想將一個循環轉換爲linq表達式。但是,接縫不工作我做的方式:如何使用外部對象編寫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 today = DateTime.Now;在表達我得到不同的錯誤的PARM ...

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

回答

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); 
+1

明亮,它幫助我理解了更多的表達式,然後在.net文檔中 – setlio

0

很難說究竟出了什麼問題沒有錯誤,但你可能需要在原來的版本檢查null在SubmittedDate,如:

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

做好預防,但編譯器指出,今天在這個範圍內將有不同的會議,所以我做了IEnumerable cOrders = customerOrders.Where((ICollection的順序,日期時間今天= DateTime.Now)=> order.SubmittedDate。 HasValue && order.SubmittedDate.Value.Month == today.Month);仍然有問題。此外,order.SubmittedDate無法解析 – setlio