How to elegantly fill an array/list with values

Anders Juul

How do I construct an array of doubles 'in a smart way'? I need it filled with 10-ish values like this,

var d = new double[] { -0.05, 0.0, 0.05};

but would prefer a more dynamic building like this

    var d = new List<double>();
    for (var dd = -0.05; dd < 0.05; dd += 0.05)
    {
        d.Add(dd);
    }

It looks chunky though and commands too much attention in my code compared to the rather mundane service performed.

Can I write it smarter?

BR, Anders

Dmitry Bychenko

Try Enumerable.Range:

  int n = 7;
  double step = 0.05; 

  double[] d = Enumerable
    .Range(-n / 2, n)
    .Select(i => i * step)
    .ToArray();

  Console.Write(string.Join("; ", d));

Outcome

-0.15; -0.1; -0.05; 0; 0.05; 0.1; 0.15

If n = 3 then we'll get

-0.05; 0; 0.05

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related