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

前端 未结 6 1028
傲寒
傲寒 2020-12-04 12:00

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

But as an

6条回答
  •  我在风中等你
    2020-12-04 12:46

    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(this IEnumerable items, Action action)
        {
            foreach (var item in items)
            {
                action(item);
            }
        }
    }
    
    [TestFixture]
    public class ForEachTests
    {
        public void Each(IEnumerable items, Action 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 static modifier and the first parameter of the method.

    This method

    public static void Each(this IEnumerable items, Action action)
    {
        foreach (var item in items)
        {
            action(item);
        }
     }
    

    becomes

    public void Each(Action action)
    {
        foreach (var item in items)
        {
            action(item);
        }
     }
    

提交回复
热议问题