Answer the question
In order to leave comments, you need to log in
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
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 + " "); } );
void Method(){
var list = new List<int>() { 1, 2, 3 };
list.ForEach(Square);
}
void Square(int element){
Console.Write(element*element + " ");
}
It is important to use .ForEach()
Here is an approach that can be used
foreach (var item in list)
{
Console.WriteLine(item.property);
}
List.ForEach(x => {
Console.WriteLine(x.property);
});
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
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 questionAsk a Question
731 491 924 answers to any question