How best to separate the two lists in C# by doing an operation with each side of the split

Asked

Viewed 86 times

0

This questioning came to my head in an activity I was doing here at work.

What would be the best way to do this operation?

The example I bring would be say we have a T object, and we have a List, if I operate for example:

objeto.Where(o => o.Data < DateTime.Now).ForEach(o => fazX());

We would have in this case logically 2 lists, but in code we have 1 only, if I wanted to operate the other part I would have to do another Where this way:

objeto.Where(o => o.Data > DateTime.Now).ForEach(o =>fazY());

That way the two parts of the list operate with different functions, but I wanted to know if there is a way to do all this only in 1 line, I believe it is possible since it seems to me a simple and common problem, I just could not find here or elsewhere.

2 answers

3


using {} you can create a scope inside the lambda function, and inside put an If

lista.ForEach(x=>  { if (x == "") FazX(); else FazY();});

In your case:

objeto.ForEach(o => { if (o.Data > DateTime.Now) fazY(); else fazX();});

ps. I think breaking the line makes it more readable.

  • Um, I didn’t think of that possibility, I thought I would have something more elegant with Linq or something like that, but I liked that solution too.

1

The Rovann solution works perfectly for your scenario, and LINQ makes the code "more beautiful". But use the .ForEach LINQ is much slower than using the foreach conventional, which in turn, in most cases (it is not always, so it should always test) is slower than the for.

I suggest using the loop for your scenario and optimizing your system performance.

for (int i = 0; i < lista.Count; i++)
{
     if (lista[i].Data > DateTime.Now)
         FazY();
     else
         FazX();
 }
  • My question really had less to do with performance and more to do with whether there was a "ala javascript" way of writing the foreach... but yes, the performance for me in this case was very important so much is that my solution was identical to yours because I needed this speed in the operation in question.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.