Massey
Massey

Reputation: 1125

Coverting a foreach loop containing an if statement into linq method syntax in C#

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

Answers (3)

MetaColon
MetaColon

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

Phuong Nguyen
Phuong Nguyen

Reputation: 3070

How about this:

MyCollection.Where(d => d.DeliveryDate.Equals("Tomorrow"))
            .ToList()
            .ForEach(d => d.DeliveryDate = MyMethodToConvert(DeliveryDate));

Upvotes: -1

Jeppe Stig Nielsen
Jeppe Stig Nielsen

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

Related Questions