编写代码以遍历数组的所有元素的最快方法

时间:2013-08-14 12:31:16

标签: c# .net arrays loops collections

很多时候我需要循环遍历数组的所有项目。如果它是List我将使用ForEach扩展方法。

我们是否也有类似的数组。

有关。例如假设我要声明一个128和128的bool数组。将所有成员初始化为true。

bool[] buffer = new bool [128];

可能有更多用例

现在将其初始化为true。有没有任何扩展方法或我需要编写传统的foreach循环??

3 个答案:

答案 0 :(得分:8)

您可以使用它来初始化数组:

bool[] buffer = Enumerable.Repeat(true, 128).ToArray();

但总的来说,没有。我不会使用Linq来编写任意循环,只是为了查询数据(毕竟,它被称为语言集成查询)。

答案 1 :(得分:1)

您可以创建一个扩展方法来初始化一个数组,例如:

public static void InitAll<T>(this T[] array, T value)
{
    for (int i = 0; i < array.Length; i++)
    {
        array[i] = value;
    }
}

并按如下方式使用:

bool[] buffer = new bool[128];
buffer.InitAll(true);

修改

为了解决这对参考类型无用的任何问题,扩展这个概念是一件简单的事情。例如,您可以添加重载

public static void InitAll<T>(this T[] array, Func<int, T> initializer)
{
    for (int i = 0; i < array.Length; i++)
    {
        array[i] = initializer.Invoke(i);
    }
}

Foo[] foos = new Foo[5];
foos.InitAll(_ => new Foo());
//or
foos.InitAll(i => new Foo(i));

这将创建5个新的Foo实例并将它们分配给foos数组。

答案 2 :(得分:-3)

您可以这样做,不要分配值,而是使用它。

        bool[] buffer = new bool[128];
        bool c = true;
        foreach (var b in buffer)
        {
            c = c && b;
        }

或使用Linq:

        bool[] buffer = new bool[128];
        bool c = buffer.Aggregate(true, (current, b) => current && b);