user1097772
user1097772

Reputation: 3529

Usage list.ForEach in C#

Lets have:

List<double> inputs,outputs;

Is any difference between this:

inputs.Clear();
outputs.ForEach(inputs.Add);

and this:

inputs.Clear();  
outputs.ForEach(x => inputs.Add(x));

1) I assume that both options will first clear list of inputs and than take all values in list of outputs and put them into list of inputs.
2) Both options looks like they are equivalent. Am I right? Is any difference between them?

Upvotes: 0

Views: 79

Answers (1)

PC Luddite
PC Luddite

Reputation: 6088

No, there's no difference. They'll most likely be compiled to the same IL code.

However, in my opinion, this form

inputs.Clear();  
outputs.ForEach(x => inputs.Add(x));

shows your intent more clearly. I probably would avoid this altogether though and just use a foreach loop to add each element to inputs. But it ultimately comes down to your personal preference.

Upvotes: 2

Related Questions