0

I'm thinking if these line of codes can be simplified using lambda expressions like using valueList.ForEach? I'm new on lambda expressions.

foreach (var item in OrderList)
{
    item.ReserveDate = DateTime.ParseExact(item.ReserveDate, "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture).ToShortDateString();
    item.ExpireDate = DateTime.ParseExact(item.ExpireDate, "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture).ToShortDateString();
}
5
  • 1
    Far from simplifying it, I think trying to use lambdas here will just make it more complicated. This code is absolutely fine as it is. Commented Feb 23, 2016 at 9:00
  • The results would be less efficient than the method you are using. The left side of the results would have to be a new variable since you can't have the same variable on both side of a lambda expression. Then you would have to take the new variable and assign it back to the OrderList. Commented Feb 23, 2016 at 9:09
  • One thing a lambda could improve here is create a more DRY approach: Func<string,sting> parse = d => DateTime.ParseExact(d, "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture).ToShortDateString(); (created before the loop) and use the lambda to assign both values item.ReserveDate = parse(item.ReserveDate); Commented Feb 23, 2016 at 9:38
  • @MatthewWatson Is it adviseable to use automapper just for this kind of problem? Commented Feb 24, 2016 at 7:16
  • @DerpukuDer Well, there's quite a bit of debate about whether one should use Automapper. Personally I wouldn't for this simple case. Commented Feb 24, 2016 at 9:08

1 Answer 1

1

You can write like this, but I don't know if it's actually more readable than foreach:

OrderList.ForEach(item => {
    item.ReserveDate = DateTime.ParseExact(item.ReserveDate, "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture).ToShortDateString();
    item.ExpireDate = DateTime.ParseExact(item.ExpireDate, "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture).ToShortDateString();
});

Unless you can use work on those in parallel (but again, readability):

Parallel.ForEach(OrderList, item => {
    item.ReserveDate = DateTime.ParseExact(item.ReserveDate, "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture).ToShortDateString();
    item.ExpireDate = DateTime.ParseExact(item.ExpireDate, "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture).ToShortDateString();
});
Sign up to request clarification or add additional context in comments.

2 Comments

I think this shows what I meant by my comment to the OP. ;)
@Matthew Is it adviseable to use automapper just for this kind of problem?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.