-1

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!

FtoB
  • 25
  • 6
  • 3
    [Arrays](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/arrays/) exist. – Theraot Dec 27 '21 at 19:55
  • Does this answer your question? [Is there a C# alternative to Java's vararg parameters?](https://stackoverflow.com/questions/18194849/is-there-a-c-sharp-alternative-to-javas-vararg-parameters) – voiarn Dec 27 '21 at 19:57
  • 1
    Any time you have variable names like X1, X2, X3, etc. then what you want is an array or collection of some kind. In C#, you might be looking for a `List`. – David Dec 27 '21 at 19:58
  • Let us say that for whatever reason you cannot have a field of type array or other collection. We could do this with reflections. Is that what you want? I would expect you to be familiar with arrays before being familiar with reflection. So, sorry if I misjudged that. You are going to need arrays anyway, see [Get field values from a simple class](https://stackoverflow.com/a/7649355/402022). – Theraot Dec 27 '21 at 20:10
  • Arrays, right. This way it works. So simple! – FtoB Dec 27 '21 at 21:10

1 Answers1

0

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();
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215