G
G
Gina Lee2016-04-01 11:02:08
Programming
Gina Lee, 2016-04-01 11:02:08

How for List.ForEach() to determine the current element?

Using List.ForEach() I work with each element of the list in turn, right? But how to determine with which one, if, for example, with a sheet element that has certain properties, I need to perform a certain operation?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
A
Arseniy Efremov, 2016-04-01
@Din7

The method List<TElement>.ForEach(Action<TElement>)takes as a parameter a delegate (that is, essentially a function pointer) that processes each element of the list.
A record like this:

var list = new List<int>() { 1, 2, 3 };
list.ForEach(element => { Console.Write(element * element + " "); } );

This will display the following on the screen: 1 4 9
This piece of code is completely equivalent to this:
void Method(){
   var list = new List<int>() { 1, 2, 3 };
   list.ForEach(Square);
}
void Square(int element){
   Console.Write(element*element + " ");
}

Thus, in both the first and second cases, the element variable is the current processed value from the list.

D
Dmitry Eremin, 2016-04-01
@EreminD

It is important to use .ForEach()
Here is an approach that can be used

foreach (var item in list)
{
Console.WriteLine(item.property);
}

if it matters, then like this:
List.ForEach(x => { 
Console.WriteLine(x.property); 
});

A
Alexander Kholodovich, 2016-04-01
@kholodovitch

If it is properties, then ForEach calls the method with the transfer of a list element to it. In this method, check what the properties are and branch the logic. Can you describe an example?
UPD : If you need to do the same thing only with elements of a certain "property" (for example, not for some - one thing, for others - another), then you need to filter them through Where by this property before ForEach

D
Dmitry Kovalsky, 2016-04-01
@dmitryKovalskiy

Using List.ForEach you perform certain actions on each object of the collection. In principle, you cannot even hope in what order they will be processed. If you need to do these actions only on objects that meet certain conditions, then first you select these elements, and then call ForEach ... i.e. not List.ForEach() but List.Where.ForEach()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question