views:

6187

answers:

3

First, I know there are methods off of the generic List<> class already in the framework do iterate over the List<>.

But as an example, what is the correct syntax to write a ForEach method to iterate over each object of a List<>, and do a Console.WriteLine(object.ToString()) on each object. Something that takes the List<> as the first argument and the lambda expression as the second argument.

Most of the examples I have seen are done as extension methods or involve LINQ. I'm looking for a plain-old method example.

+17  A: 
public void Each<T>(IEnumerable<T> items, Action<T> action)
{
    foreach (var item in items)
        action(item);
}

... and call it thusly:

Each(myList, i => Console.WriteLine(i));
Matt Hamilton
Cool. Now where does the Func<> syntax that I have seen around come into play?
tyndall
Func<> delegates are generic delegates for methods with return values. Action<> delegates are generic delegates for methods WITHOUT return values. Thats the only difference.
TheSoftwareJedi
so in your case, you don't need to return something (from console.writeline - so Action<T> is sufficient.
TheSoftwareJedi
+4  A: 

The above could also be written with less code as:

new List<SomeType>(items).ForEach(
    i => Console.WriteLine(i)
);

This creates a generic list and populates it with the IEnumerable and then calls the list objects ForEach.

Peanut
The question asked how to write the method (not how to call it), and specified that he did not want to use LINQ or Extension methods.
StriplingWarrior
A: 

You can traverse each string in the list and even you can search in the whole generic using a single statement this makes searching easier.

public static void main(string[] args) { List names = new List();

names.Add(“Saurabh”); names.Add("Garima"); names.Add(“Vivek”); names.Add(“Sandeep”);

string stringResult = names.Find( name => name.Equals(“Garima”)); }