0

如何将以下代码转换为方法运算符:

var myOrders = from c in customers
               where c.Field<string>("Region") == "WA"
               from o in orders
               where c.Field<string>("CustomerID") == o.Field<string>("CustomerID")
               && (DateTime)o["OrderDate"] >= cutoffDate
               select new { 
                  CustomerID = c.Field<string>("CustomerID"), 
                  OrderID = o.Field<int>("OrderID") 
               };

- - - - -或者 - - - - -

 var myOrders = from c in customers
               where c.Region == "WA"
               from o in orders
               where c.CustomerID == o.CustomerID
               && o.OrderDate >= cutoffDate
               select new { 
                  CustomerID = c.CustomerID, 
                  OrderID = o.OrderID 
               };

对象形式的相同代码

4

3 回答 3

2

我实际上会将其重写为连接 - 可能通过中间变量:

var washingtonCustomers = customers.Where(c => c.Field<string>("Region") == "WA");
var recentOrders = orders.Where(o => (DateTime)o["OrderDate"] >= cutoffDate);

var query = washingtonCustomers.Join(recentOrders, 
                 c => c.Field<string>("CustomerID"),
                 o => o.Field<string>("CustomerID"),
                 (c, o) => new { 
                     CustomerID = c.Field<string>("CustomerID"), 
                     OrderID = o.Field<int>("OrderID") 
                 });
于 2012-09-19T17:42:43.453 回答
0

您是否只想使用功能性 Linq 语法而不是查询语法?那看起来像:

var myOrders = customers
  .Where(c => c.Region == "WA")
  .SelectMany(c => 
    orders
      .Where(o => (o.CustomerID == c.CustomerID)
        && (o.OrderDate > cutoffDate))
      .Select(o => new {
           CustomerID = c.CustomerID,
           OrderID = o.OrderID
         })
   );
于 2012-09-19T17:40:25.033 回答
0

您可以尝试使用此代码 - 基于 IEnumerable<KeyValuePair<string, Int32>

public  IEnumerable<KeyValuePair<string, Int32>> YourQuery(DateTime date, string code)
{

           var result = 
           from c in customers
           where c.Field<string>("Region") == code

           from o in orders
           where c.Field<string>("CustomerID") == o.Field<string>("CustomerID")
               && (DateTime)o["OrderDate"] >= date

           select new 
           { 
              CustomerID = c.Field<string>("CustomerID"), 
              OrderID = o.Field<int>("OrderID") 
           };

           return result;
}
于 2012-09-19T17:40:45.030 回答