LINQ equivalent of foreach for IEnumerable

后端 未结 22 2259
夕颜
夕颜 2020-11-21 22:54

I\'d like to do the equivalent of the following in LINQ, but I can\'t figure out how:

IEnumerable items = GetItems();
items.ForEach(i => i.DoS         


        
22条回答
  •  情歌与酒
    2020-11-21 23:33

    I took Fredrik's method and modified the return type.

    This way, the method supports deferred execution like other LINQ methods.

    EDIT: If this wasn't clear, any usage of this method must end with ToList() or any other way to force the method to work on the complete enumerable. Otherwise, the action would not be performed!

    public static IEnumerable ForEach(this IEnumerable enumeration, Action action)
    {
        foreach (T item in enumeration)
        {
            action(item);
            yield return item;
        }
    }
    

    And here's the test to help see it:

    [Test]
    public void TestDefferedExecutionOfIEnumerableForEach()
    {
        IEnumerable enumerable = new[] {'a', 'b', 'c'};
    
        var sb = new StringBuilder();
    
        enumerable
            .ForEach(c => sb.Append("1"))
            .ForEach(c => sb.Append("2"))
            .ToList();
    
        Assert.That(sb.ToString(), Is.EqualTo("121212"));
    }
    

    If you remove the ToList() in the end, you will see the test failing since the StringBuilder contains an empty string. This is because no method forced the ForEach to enumerate.

提交回复
热议问题