Atul Sureka
Atul Sureka

Reputation: 3302

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. e.g. 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??

Upvotes: 4

Views: 195

Answers (3)

Patrick McDonald
Patrick McDonald

Reputation: 65421

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.

Upvotes: 1

Daniel
Daniel

Reputation: 9521

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

Upvotes: -3

p.s.w.g
p.s.w.g

Reputation: 148990

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

Upvotes: 8

Related Questions