简体   繁体   中英

Quickest way to write code to loop over all elements of array

Many times I need to loop over all the items of an array. If it was List I would have used ForEach extension method.

Do we have anything similar for arrays as well.

For. eg lets say I want to declare an array of bool of size 128 & initialize all members to true.

bool[] buffer = new bool [128];

There can be many more use cases

Now initialize it to true. is there any extension method or do I need to write traditional foreach loop??

You could use this to initialize the array:

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

But in general, no. I wouldn't use Linq for writing arbitrary loops, only for querying the data (after all, it's called Language-Integrated Query).

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.

You can do that not to assign a value but to use it.

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

Or using Linq:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM