I am wondering how I could make a calculation (in this case, calculating the average) with a variable number of variables / fields in C#? I could write an if case for each number of variables but I bet there is a better way for it, right? The bad way would like this:
if (numberOfFields == 4)
(field1 field2 field3 field4) / 4;
if (numberOfFields == 5)
(field1 field2 field3 field4 field5) / 5;
.
.
.
Greetings!
CodePudding user response:
Organize your variables (field1, field2...
) into a collection, say, array (you can well use List<T>
and many other collections):
//TODO: put the right type here
double[] array = new double[] {
field1,
field2,
field3,
field4,
field5,
...
};
Then query with a help of LInq:
using System.Linq;
...
var average = array
.Take(numberOfFields)
.Average();