簡體   English   中英

如何在C#LINQ ForEach循環中執行多個操作

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

我有一個Question對象列表,我使用ForEach迭代列表。 對於每個對象,我執行.Add將其添加到我的實體框架中,然后添加到數據庫中。

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

我需要修改ForEach中的每個對象,並將AssignedDate字段設置為DateTime.Now 有沒有辦法可以在ForEach循環中執行此操作?

你會做的事情

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

看一下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
 */
foreach(var itemToAdd in add)
{
   Do_first_thing(itemToAdd);
   Do_Second_Thing(itemToAdd);
}

或者如果你堅持在List<>上使用ForEach方法

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

就個人而言,我會選擇第一個,它更清晰。

很可能你不需要這樣做。 只需使用簡單的foreach

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

除非有特殊原因要使用lambda,否則foreach更清晰,更易讀。 作為額外的獎勵,它不會強迫您將問題集合實現到列表中,最有可能減少應用程序的內存占用。

使用foreach聲明

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

或作為旁觀者提議做_obj.AssignedDate = DateTime.Now; .ForEach(方法

像這樣

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM