Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I do multiple operations inside a C# LINQ ForEach loop

Tags:

c#

You would do something like

add.ForEach(_obj =>
                {
                    _uow.Questions.Add(_obj);
                    Console.WriteLine("TADA");
                });

Have a look at the examples in Action Delegate

The following example demonstrates the use of the Action delegate to print the contents of a List object. In this example, the Print method is used to display the contents of the list to the console. In addition, the C# example also demonstrates the use of anonymous methods to display the contents to the console. Note that the example does not explicitly declare an Action variable. Instead, it passes a reference to a method that takes a single parameter and that does not return a value to the List.ForEach method, whose single parameter is an Action delegate. Similarly, in the C# example, an Action delegate is not explicitly instantiated because the signature of the anonymous method matches the signature of the Action delegate that is expected by the List.ForEach method.

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        List<String> names = new List<String>();
        names.Add("Bruce");
        names.Add("Alfred");
        names.Add("Tim");
        names.Add("Richard");

        // Display the contents of the list using the Print method.
        names.ForEach(Print);

        // The following demonstrates the anonymous method feature of C# 
        // to display the contents of the list to the console.
        names.ForEach(delegate(String name)
        {
            Console.WriteLine(name);
        });

        names.ForEach(name =>
        {
            Console.WriteLine(name);
        });
    }

    private static void Print(string s)
    {
        Console.WriteLine(s);
    }
}
/* This code will produce output similar to the following:
 * Bruce
 * Alfred
 * Tim
 * Richard
 * Bruce
 * Alfred
 * Tim
 * Richard
 */

foreach(var itemToAdd in add)
{
   Do_first_thing(itemToAdd);
   Do_Second_Thing(itemToAdd);
}

or if you will insist on using the ForEach method on List<>

add.ForEach(itemToAdd  => 
{
   Do_first_thing(itemToAdd);
   Do_Second_Thing(itemToAdd);
});

Personally I'd go with the first, it's clearer.


Most likely you don't need to do things this way. Just use a plain foreach:

foreach (var question in problem.Questions)
{
    question.AssignedDate = DateTime.Now;
    _uow.Questions.Add(question);
}

Unless there is specific reason to use a lambda, a foreach is cleaner and more readable. As an added bonus it does not force you to materialize the collection of questions into a list, most likely reducing your application's memory footprint.