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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18230690/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 11:35:09  来源:igfitidea点击:

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

c#

提问by

I have a list of Question objects and I use a ForEachto iterate through the list. For each object I do an .Addto add it into my entity framework and then the database.

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

List<Question> add = problem.Questions.ToList();
add.ForEach(_obj => _uow.Questions.Add(_obj));

I need to modify each of the objects in the ForEachand set the AssignedDatefield to DateTime.Now. Is there a way I can do this inside of the ForEachloop?

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

采纳答案by Adriaan Stander

You would do something like

你会做类似的事情

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

Have a look at the examples in Action Delegate

查看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.

下面的示例演示如何使用 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
 */

回答by No Idea For Name

use a foreach statement

使用 foreach 语句

foreach (Question q in add)
{
   _uow.Questions.Add(q);
   q.AssignedDate = DateTime.Now;
}

or as astander propose do _obj.AssignedDate = DateTime.Now;in the .ForEach(method

或作为旁观者_obj.AssignedDate = DateTime.Now;.ForEach(方法中提出

回答by Binary Worrier

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

or if you will insist on using the ForEachmethod on List<>

或者如果您坚持使用该ForEach方法List<>

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

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

我个人会选择第一个,它更清楚。

回答by Jon

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

您很可能不需要以这种方式做事。只需使用一个普通的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 foreachis 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.

除非有使用 lambda 的特殊原因,否则 aforeach会更清晰且更具可读性。作为一个额外的好处,它不会强迫您将问题集合具体化为一个列表,很可能会减少应用程序的内存占用。

回答by Ehsan

Like this

像这样

add.ForEach(_obj =>
                    {
                        _obj.AssignedDate = DateTime.Now;
                        _uow.Questions.Add(_obj);

                    });

回答by Katu

add.ForEach(delegate(Question q)
    {
        // This is anonymous method and you can do what ever you want inside it.
        // you can access THE object with q
        Console.WriteLine(q);
    });