4

配列のすべての項目を何度もループする必要があります。List の場合、ForEach 拡張メソッドを使用していたでしょう。

配列にも同様のものがありますか。

為に。たとえば、サイズ 128 の bool の配列を宣言し、すべてのメンバーを true に初期化するとします。

bool[] buffer = new bool [128];

もっと多くのユースケースがあるかもしれません

ここで true に初期化します。拡張メソッドはありますか、それとも従来の foreach ループを記述する必要がありますか??

4

3 に答える 3

8

これを使用して配列を初期化できます。

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

しかし、一般的には、いいえ。任意のループを記述するために Linq を使用するのではなく、データのクエリを実行するためだけに使用します (結局のところ、Language-Integrated Query と呼ばれます)。

于 2013-08-14T12:32:36.580 に答える
1

You could create an extension method to initialize an array, for example:

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

and use it as follows:

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

Edit:

To address any concerns that this isn't useful for reference types, it's a simple matter to extend this concept. For example, you could add an overload

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

This will create 5 new instances of Foo and assign them to the foos array.

于 2013-08-14T12:53:12.363 に答える
-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);
于 2013-08-14T12:36:58.090 に答える