Вопрос

I have never used generics before and was wondering how to constrain the Type to either Double[] or List<Double> (or if this is even the correct thing to do). I need to calculate the average of many numbers that are sometimes known in advance (i.e. I can create an array of exact size) but, at other times, are generated immediately before the calculation (i.e. I use a List).

I would like this generic method Average(T arrayOrList) to be able to accept an array or list instead of overloading the Average() method.

Thanks!

Это было полезно?

Решение

Since both double[] and List<double> implement IEnumerable<double>, I'd suggest the following:

public double Average(IEnumerable<double> arrayOrList) {
    // use foreach to loop through arrayOrList and calculate the average
}

That's simple subtype polymorphism, no generics required.

As others have already mentioned, if you simply want to calculate an average, such a method already exists in the framework.

Другие советы

I would just use IEnumerable<double>, since all you need to do is loop over the data (and both lists and arrays support this, as do deferred sequences).

In fact, Microsoft got there first:

var avg = sequence.Average();

http://msdn.microsoft.com/en-us/library/bb358946.aspx

Why not just write a function that accepts an IEnumerable<double>?

Then if you really want to use an ArrayList, I assume not by choice you can use the AsEnumerable() extensions.

EDIT, seems I miread ArrayOrList, but the answer still applies, although it was 56 secs late

var x = new List(); var average = x.Average(); var y = new Double[10]; var average = y.Average();

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top