The fastest way to write code for a loop over all elements of an array

Many times I need to iterate over all the elements of an array. If it were a List, I would use the ForEach extension method.

We have something similar for arrays.

For. for example, say I want to declare a 128 bool array and initialize all members to true.

bool[] buffer = new bool [128]; 

There may be many other uses.

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

+4
source share
3 answers

You can create an extension method to initialize the 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 solve any problems that are not suitable for reference types, the simple task is to extend this concept. For example, you can add 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 Foo instances and assign them to the foos array.

+1
source

You can use this to initialize an array:

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

But in general, no. I would not use Linq to write arbitrary loops, only to query data (after all, it was called Language-Integrated Query).

+8
source

You can do this 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); 
-3
source

Source: https://habr.com/ru/post/1497017/


All Articles