2

In C++, we can set a range of values of an array(and other similar containers) using fill.

For example,

fill(number, number+n,10);

The above code will set the first n values of the array number with the value 10.

What is the closest C# equivalent to this.

Shamim Hafiz - MSFT
  • 21,454
  • 43
  • 116
  • 176

3 Answers3

4

There's no equivalent method but there are many ways to write similar code

Methods from the Linq-to-Objects classes can create sequences that you can use to initialize lists but this is very different from how things in C++ actually occur.

new List<char>(Enumerable.Repeat('A', 10));
new List<int>(Enumerable.Range(1, 10));

C++ can accomplish these things more generally thanks to how C++ templates work, and while simple type constraints in C# help, they do not offer the same flexibility.

John Leidegren
  • 59,920
  • 20
  • 131
  • 152
  • 1
    Why not use `ToList` on the result of `Repeat`, and thus avoid needing to explicitly specify the list type? – Richard Aug 05 '11 at 10:39
  • @Richard I don't see why not, there are many ways to construct lists, I really like type inference but used the constructors in this example. – John Leidegren Aug 05 '11 at 10:41
4

I'm not sure one exists, but you can code your own easily:

void Fill<T>(T[] array, int start, int count, T value)
{
  for (int i = start, j = 0; j < count; i++, j++)
    array[i] = value;
}

Obviously missing parameter checking, but you get the drill.

jakobbotsch
  • 6,167
  • 4
  • 26
  • 39
3

There is no direct equivalent, but you can do it in two steps. First use Enumerable.Repeat to create an array with the same value in each element. Then copy that over the destination array:

var t = Enumerable.Repeat(value, count).ToArray();
Array.Copy(t, 0, dest, destStartIndex, count);

For other destination containers there is a lack of an equivalent to Array.Copy, but it is easy to add these as destinations, eg:

static void Overwrite<T>(this List<T> dest, IEnumerable<T> source, int destOffset) {
  int pos = destOffset;
  foreach (var val in source) {
    // Could treat this as an error, or have explicit count
    if (pos = dest.Length) { return; }

    dest[pos++] = val;
  }
}
Richard
  • 106,783
  • 21
  • 203
  • 265
  • Should probably just make a `Fill` extension method if that's what you need. This is rather expensive (even if it's a more general solution to the problem). Also, if we change the parameter `List dest` to `IList dest` it should work on arrays as well as lists. – John Leidegren Aug 05 '11 at 10:48