如何在C#LINQ ForEach循环中执行多个操作

30 c#

我有一个Question对象列表,我用a ForEach来遍历列表.对于每个对象,我都会将.Add其添加到我的实体框架中,然后添加到数据库中.

List<Question> add = problem.Questions.ToList();
add.ForEach(_obj => _uow.Questions.Add(_obj));
Run Code Online (Sandbox Code Playgroud)

我需要修改其中的每个对象ForEach并将AssignedDate字段设置 为DateTime.Now.有没有办法在ForEach循环中做到这一点?

Adr*_*der 54

你会做的事情

add.ForEach(_obj =>
                {
                    _uow.Questions.Add(_obj);
                    Console.WriteLine("TADA");
                });
Run Code Online (Sandbox Code Playgroud)

看一下Action Delegate中的示例

以下示例演示如何使用Action委托来打印List对象的内容.在此示例中,Print方法用于向控制台显示列表的内容.此外,C#示例还演示了使用匿名方法向控制台显示内容.请注意,该示例未显式声明Action变量.相反,它传递对一个方法的引用,该方法接受一个参数并且不向List.ForEach方法返回一个值,该方法的单个参数是一个Action委托.类似地,在C#示例中,未明确实例化Action委托,因为匿名方法的签名与List.ForEach方法所期望的Action委托的签名匹配.

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
 */
Run Code Online (Sandbox Code Playgroud)