nin
nin

Reputation: 253

Convert from query to method

How to convert following code to method operator:

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") 
               };

---------or----------

 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 
               };

same code in object form

Upvotes: 0

Views: 104

Answers (3)

Drew Shafer
Drew Shafer

Reputation: 4802

Are you just wanting to use the functional Linq syntax instead of query syntax? That would look like:

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
         })
   );

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500055

I'd actually rewrite this as a join - probably via intermediate variables:

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") 
                 });

Upvotes: 2

Aghilas Yakoub
Aghilas Yakoub

Reputation: 28970

You can try with this code - based on 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;
}

Upvotes: 0

Related Questions