0

I want to set a same value for a specific range of an array or list without using a loop. It would look as follows:

int[] myArray = new int[100]; 
int lower = 20; 
int upper = 80; 
int value = 5;

myArray.Method(lower,upper,value);

I have tried myArray.SetValue() and also myList.InsertRange() but it only allows to set one value, not a range.

Is any C#-Method doing that task? Could that be done without a loop?

4
  • 2
    A for loop seems to be the obvious choice. What's wrong with that? Commented Jun 27, 2014 at 9:51
  • 1
    Are you looking for an existing framework solution, or is it ok to create your own Extension Method? Commented Jun 27, 2014 at 9:53
  • 1
    You're gonna use a loop somehow, it's only a question of where you hide it. Commented Jun 27, 2014 at 9:56
  • @sloth I am just curious. It happens so often that I am substituting my for loops for methods that I did not know before... Commented Jun 27, 2014 at 9:57

2 Answers 2

2

Well, you could create a temporary array in the right size and copy it into your source array

Array.Copy(Enumerable.Repeat(value, upper-lower+1).ToArray(), 0,
           myArray, lower, upper-lower+1);

but that's very inefficient (and, internally, Enumerable.Repeat uses a loop, too)

I don't see what's wrong with a simple for loop:

for(int i = lower; i <= upper; i++)
    myArray[i] = value;
Sign up to request clarification or add additional context in comments.

Comments

1

You require a loop somewhere, because the hardware you work on most likely does not support this type of operation.

Here is a generic extension method that will work on all array types according to your specification:

class Program
{
    static void Main(string[] args)
    {
        int[] ints = new int[5];
        ints.UpdateRange(2, 4, 5);
        //ints has value [0,0,5,5,0]
    }
}

public static class ArrayExtensions
{
    public static void UpdateRange<T>(this T[] array, int lowerBound, int exclusiveUpperBound, T value)
    {
        Contract.Requires(lowerBound >= 0, "lowerBound must be a positive number");
        Contract.Requires(exclusiveUpperBound > lowerBound, "exclusiveUpperBound must be greater than lower bound");
        Contract.Requires(exclusiveUpperBound <= array.Length, "exclusiveUpperBound must be less than or equal to the size of the array");

        for (int i = lowerBound; i < exclusiveUpperBound; i++) array[i] = value;
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.