Using Enumerable to initialize an array of arrays with the same value in C#

Im new in C# I just want to know if it's possible to initialize an array of arrays with the same value using Enumerable, what I'm trying to do is something like this:

Enumerable.Range(1, 8).Select(i => {-1, -1}).ToArray();

or using Repeat

Enumerable.Repeat({ -1, -1}, 8).ToArray();

My desired output would be an array with this shape and values:

{{-1, -1}, {-1, -1}, {-1, -1}, {-1, -1}, {-1, -1}, {-1, -1}, {-1, -1}, {-1, -1} };
  1. Can this be achieved using Enumerable?
  2. Is there any other "short" way to do this?

Thanks for your help.

Upvotes: 1

Views: 435

Answers (2)

Michael Sander
Michael Sander

Reputation: 2737

You almost had it with your first aproach, try

Enumerable.Range(1, 8).Select(i => new [] { -1, -1 }).ToArray();

Upvotes: 4

Peter Duniho
Peter Duniho

Reputation: 70652

IMHO, Repeat() is a better choice. Again, you were close:

Enumerable.Repeat(new[] { -1, -1 }, 8).ToArray();

You only can omit the new[] with initializers (e.g. when declaring a variable).

Upvotes: 5

Related Questions