2

Using method syntax I can print to console all orders of $100

foreach (var order in orders.Where(o => o.Amount == 100))
   Console.WriteLine("Order: {0} - Order Amount: {1}", order.OrderID, order.Amount);

But to do this using query syntax, I have to create a var first to store the results before my Console.WriteLine loop:

var summary = from o in orders
              where o.Amount == 100 
              select o;                                        
foreach (var order in summary)
   Console.WriteLine("Order: {0} - Order Amount: {1}", order.OrderID, order.Amount);

Can this query syntax be reduced to eliminate the declaration of summary?

4

2 回答 2

5

您是否尝试过将查询包装在括号中?

foreach (var order in (from o in orders
          where o.Amount == 100 
          select o))

您也可以考虑使用ForEach扩展名List在此处记录),如下所示:

 (from o in orders 
  where o.Amount == 100 
  select o)
 .ToList().ForEach(o => Console.WriteLine(...))
于 2013-06-08T03:15:28.563 回答
1
foreach (var order in (from o in orders
              where o.Amount == 100 
              select o))
{
    // ...
}

应该可以工作 - 查询将首先返回您的列表,然后由foreach. 该查询基本上只是由运行时翻译成(或多或少)与您的第一个示例相同的方法语法。

于 2013-06-08T03:15:03.807 回答