4

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??

1
  • A 'traditional foreach loop' won't let you alter the contents. Commented Aug 14, 2013 at 12:58

3 Answers 3

8

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

Sign up to request clarification or add additional context in comments.

Comments

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.

3 Comments

this isn't useful for reference types.
Lot's of things aren't useful for reference types
@DanielA.White It's useful if you want to make all elements of the array reference the same object.
-3

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

4 Comments

Nope, you can´t modify b during enumeration.
I know but this answer depends on the usage
The OP wants to modify! That was the question.
I don't think OP is confused about how to write foreach loops, but is wondering if there's another way. Also your Linq example could be simplified to buffer.All(b => b)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.