Reputation: 1125
I am trying to convert this to a linq statement with method syntax. I am not sure how to do it when teh foreach loop has an if statement. In the code below, MyMethodToConvert replaces the string "Tomorrow" to DateTime.Now
foreach (var data in MyCollection)
{
if (data.DeliveryDate.Equals("Tomorrow"))
{
data.DeliveryDate = MyMethodToConvert(DeliveryDate);
}
}
I tried this, t didn't work
MyCollection = MyCollection.Select(a =>
{
a.DeliveryDate.Equals("Tomorrow")
? MyMethodToConvert(DeliveryDate)
: a.DeliveryDate)
;
return a;
}).ToList();
But it didn't work.
Upvotes: 0
Views: 93
Reputation: 2871
You could use this:
MyCollection = MyCollection.Select(data =>
{
if (data.DeliveryDate.Equals("Tomorrow"))
data.DeliveryDate = MyMethodToConvert(DeliveryDate);
return data;
}).ToList();
Or, if you don't want any Semicolons in your code (I'll assume that you have a class named Delivery with a constructor just for the DeliveryDate):
MyCollection = MyCollection.Select(data => data.DeliveryDate.Equals("Tomorrow")
? new Delivery(MyMethodToConvert(DeliveryDate))
: data).ToList();
However, I wouldn't suggest to use Linq in here. The only little bit useful use of Linq would be what Jeppe Stig Nielsen suggested.
Upvotes: 0
Reputation: 3070
How about this:
MyCollection.Where(d => d.DeliveryDate.Equals("Tomorrow"))
.ToList()
.ForEach(d => d.DeliveryDate = MyMethodToConvert(DeliveryDate));
Upvotes: -1
Reputation: 61952
Go only this far:
foreach (var data in MyCollection.Where(x => x.DeliveryDate.Equals("Tomorrow")))
{
data.DeliveryDate = MyMethodToConvert(DeliveryDate);
}
If the compile-time type of x.DeliveryDate
is string
, prefer:
foreach (var data in MyCollection.Where(x => x.DeliveryDate == "Tomorrow"))
{
data.DeliveryDate = MyMethodToConvert(DeliveryDate);
}
Upvotes: 4