C#代码简化查询:顺序Foreach循环

Bri*_*ian 6 c#

假设我有一些看起来像这样的代码:

foreach(type x in list y)
{
   //dostuff1(x)
}

foreach(type x in list y)
{
   //dostuff2(x)
}

foreach(type x in list y)
{
   //dostuff3(x)
}

foreach(type x in list y)
{
   //dostuff4(x)
}

foreach(type x in list y)
{
   //dostuff5(x)
}
Run Code Online (Sandbox Code Playgroud)

我无法将事物组合成一个像这样的大循环:

foreach (type x in list y)
{
    //dostuff1(x)
    //dostuff2(x)
    //dostuff3(x)
    //dostuff4(x)
    //dostuff5(x)
}
Run Code Online (Sandbox Code Playgroud)

这样做会改变顺序.有关在C#中使代码更简单的最佳方法的任何评论?

我想我可以通过创建这样的函数来解决这个问题,尽管我宁愿保持它的方式而不是强迫我的代码的未来读者理解yield:

void func(type x)
{
    dostuff1(x)
    yield 0;
    dostuff2(x)
    yield 0;
    dostuff3(x)
    yield 0;
    dostuff4(x)
    yield 0;
    dostuff5(x)
    yield break;
}

for (int i = 0; i<5; ++i)
{
   foreach (type x in list y)
   {
       //Call func(x) using yield semantics, which I'm not going to look up right now
   }
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 30

另一种选择:

List<Action<Foo>> actions = new List<Action<Foo>> { 
    doStuff1, doStuff2, doStuff3, doStuff4, doStuff5
};

foreach (Action<Foo> action in actions)
{
    foreach (Foo x in list)
    {
        action(x);
    }
}
Run Code Online (Sandbox Code Playgroud)

刚检查,这是有效的.例如:

using System;
using System.Collections.Generic;

public class Test
{
    static void Main(string[] args)
    {
        var actions = new List<Action<string>> {
            First, Second
        };

        foreach (var action in actions)
        {
            foreach (string arg in args)
            {
                action(arg);
            }
        }
    }

    static void First(string x)
    {
        Console.WriteLine("First: " + x);
    }

    static void Second(string x)
    {
        Console.WriteLine("Second: " + x);
    }
}
Run Code Online (Sandbox Code Playgroud)

跑步的结果 Test.exe a b c

First: a
First: b
First: c
Second: a
Second: b
Second: c
Run Code Online (Sandbox Code Playgroud)


Grz*_*nio 5

如果你有一个相当常量的动作列表,你可以避免使用foreach循环,但仍然显式地执行动作(尚未测试代码):

list.ForEach(action1);
list.ForEach(action2);
list.ForEach(action3);
list.ForEach(action4);
Run Code Online (Sandbox Code Playgroud)


Cha*_*ers 5

Jon Skeet的答案很棒(我刚刚投了票).这是一个进一步发展的想法:

如果你做了很多,你可以制作一个名为"DoActionsInOrder"的扩展方法(或者你可以想出一个更好的名字).这是个主意:

public static void DoActionsInOrder<T>(this IEnumerable<T> stream, params Action<T> actionList)
{
     foreach(var action in actionList)
     {
          foreach(var item in stream)
          {
               action(item);
          }
     }
}
Run Code Online (Sandbox Code Playgroud)

然后,你可以像这样调用它:

myList.DoActionsInOrder(doStuff1, doStuff2, doStuff3, doStuff4, doStuff5);
Run Code Online (Sandbox Code Playgroud)