51

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.

7 Answers 7

80
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));
Sign up to request clarification or add additional context in comments.

4 Comments

Cool. Now where does the Func<> syntax that I have seen around come into play?
Func<> delegates are generic delegates for methods with return values. Action<> delegates are generic delegates for methods WITHOUT return values. Thats the only difference.
so in your case, you don't need to return something (from console.writeline - so Action<T> is sufficient.
Also, you can just use the methodgroup "Console.WriteLine" instead of the lambda "i => Console.WriteLine(i)"
58

Is this what you're asking for?

int[] numbers = { 1, 2, 3 };
numbers.ToList().ForEach(n => Console.WriteLine(n));

3 Comments

yes. this handy and I have used it. +1. At the time I asked the question I think I was just trying to get a handle on basic C# lambda syntax when used with generics.
Ok, but we have to consider that ToList() is an O(n) operation
@ToniRossmann If your goal is to print out all the elements in the array, then iterating over the entire collection is necessary, and it will inherently be an O(n) operation. There's no way around that if you need to process each element.
43

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.

2 Comments

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.
This is convenient, but isn't the overhead of creating a new list (implying iterating over the items at least one additional time) usually not worth it?
16
public static void Each<T>(this IEnumerable<T> items, Action<T> action) {
foreach (var item in items) {
    action(item);
} }

... and call it thusly:

myList.Each(x => { x.Enabled = false; });

1 Comment

A plus for showing the way to do multiple operation in Each.
4

Want to put out there that there is not much to worry about if someone provides an answer as an extension method because an extension method is just a cool way to call an instance method. I understand that you want the answer without using an extension method. Regardless if the method is defined as static, instance or extension - the result is the same.

The code below uses the code from the accepted answer to define an extension method and an instance method and creates a unit test to show the output is the same.

public static class Extensions
{
    public static void Each<T>(this IEnumerable<T> items, Action<T> action)
    {
        foreach (var item in items)
        {
            action(item);
        }
    }
}

[TestFixture]
public class ForEachTests
{
    public void Each<T>(IEnumerable<T> items, Action<T> action)
    {
        foreach (var item in items)
        {
            action(item);
        }
    }

    private string _extensionOutput;

    private void SaveExtensionOutput(string value)
    {
        _extensionOutput += value;
    }

    private string _instanceOutput;

    private void SaveInstanceOutput(string value)
    {
        _instanceOutput += value;
    }

    [Test]
    public void Test1()
    {
        string[] teams = new string[] {"cowboys", "falcons", "browns", "chargers", "rams", "seahawks", "lions", "heat", "blackhawks", "penguins", "pirates"};

        Each(teams, SaveInstanceOutput);

        teams.Each(SaveExtensionOutput);

        Assert.AreEqual(_extensionOutput, _instanceOutput);
    }
}

Quite literally, the only thing you need to do to convert an extension method to an instance method is remove the static modifier and the first parameter of the method.

This method

public static void Each<T>(this IEnumerable<T> items, Action<T> action)
{
    foreach (var item in items)
    {
        action(item);
    }
 }

becomes

public void Each<T>(Action<T> action)
{
    foreach (var item in items)
    {
        action(item);
    }
 }

Comments

1

Standard:

foreach (Item i in allItems)
{
   i.FK_ItemStatus_CustomCodeID = itemStatuses.Where(
      x => x.CustomCodeID == i.ItemStatus_CustomCodeID).FirstOrDefault();                        
}

Lambda:

allItems.ForEach(
   i => i.FK_ItemStatus_CustomCodeID = 
      itemStatuses.Where(
         x => x.CustomCodeID == i.ItemStatus_CustomCodeID).FirstOrDefault()
      );

Comments

0

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”));
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.