Reputation: 2604
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
Upvotes: 0
Views: 115
Reputation: 186668
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
Upvotes: 2
Reputation: 4796
All this depends on what you would call "Smart Way". Performance ? Readability ? Maintenance ?
On one hand, if you have only three elements and the values are static, your first line of code is perfectly fine and it is the "Smartest Way". A small improvement would be (if you want a list) :
List<double> d = new List<double> { -0.05, 0, 0.05 };
On another hand, if you have lots of values, a for loop may be easier to write.
Linq is also possible so writing something like this :
List<double> d = Enumerable.Range(-1,3).Select(x => x * 0.05).ToList();
is really good looking because you are using Linq and it rocks, but is it really more readable ? More performant ? Smarter ?
All in all, it all depends on what you want and what you need to do. There is no straight answer to your question.
Upvotes: 2
Reputation: 81483
Another approach if you are initalzing a lot of array, you might want to use IEnumerable
and yield
in a helper class
public static IEnumerable<double> RangeEx(double start, double finish, double step)
{
for (var dd = start; dd < finish; dd += step)
yield return dd;
}
Usage
var array = RangeEx(-0.05, 0.05, 0.05).ToArray();
Upvotes: 0
Reputation: 9461
You can use linq, not quite sure if it is smart:
double start = -0.05;
double step = 0.05;
var result = Enumerable.Repeat(0, 3).Select((x, i) =>start+step*i).ToArray();
Upvotes: 0