C# 语法 - Lambda 表达式示例 - ForEach() over Generic List

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/339199/
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-03 23:47:59  来源:igfitidea点击:

C# Syntax - Example of a Lambda Expression - ForEach() over Generic List

c#.netsyntaxlambda

提问by BuddyJoe

First, I know there are methods off of the generic List<>class already in the framework do iterate over the List<>.

首先,我知道List<>框架中已有的泛型类的方法会迭代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.

但举个例子,编写 ForEach 方法来迭代List<>aConsole.WriteLine(object.ToString())的每个对象并在每个对象上执行 a的正确语法是什么。将 theList<>作为第一个参数,将 lambda 表达式作为第二个参数的东西。

Most of the examples I have seen are done as extension methods or involve LINQ. I'm looking for a plain-old method example.

我见过的大多数示例都是作为扩展方法完成的或涉及 LINQ。我正在寻找一个普通的方法示例。

采纳答案by Matt Hamilton

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

回答by Peanut

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.

这将创建一个通用列表并使用 IEnumerable 填充它,然后调用 ForEach 列表对象。

回答by Peanut

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

回答by Mauro Torres

Is this what you're asking for?

这是你要的吗?

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

回答by Krzysztof Radzimski

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

回答by Ryan Rodemoyer

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 staticmodifier and the first parameter of the method.

从字面上看,将扩展方法转换为实例方法唯一需要做的就是删除static修饰符和方法的第一个参数。

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