Use List.Average() in MonoDevelop

Hello

Why isn’t the function System.Collections.Generic.List.Average() present when working in Unity3D?

When I copy the code below into Visual Studio C# it all compiles find but in MonoDevelop I get a compiler error saying that there is no function called Average():

// The following is valid code in Visual Studio C# but not in MonoDevelop??
System.Collections.Generic.List<double> a = new System.Collections.Generic.List<double>();
double average = a.Average();

Whats going wrong? Am I including an older/wrong version of .NET?

using UnityEngine; using System.Collections; using System.Collections.Generic; ensure you are using Generics at the top.

2 Answers

2

I believe that’s a LINQ extension method.

You probably need to do a:

using System.Linq;

Ah yes. You are correct sir.

Great, can you mark it the correct answer yet? Or do you have to get more reputation to do that.

i believe the person who asked the question is the only one who can mark the question as answered. maybe high level mods too.

Great, thanks.

The answer is quite simple, unity doesn’t use .Net.

Unity uses mono (2.6 as far as I remember which mostly equals .Net 3.0 and also have some .Net 3.5 functions / classes).

In general if you want to know what’s available, see this page:

http://docs.unity3d.com/410/Documentation/ScriptReference/MonoCompatibility.html

Linq is available in Unity, I've used it myself. Just need to add a using statement.

The Linq Average method has overloads for all numeric types. No run tiem casting needed. https://msdn.microsoft.com/en-us/library/system.linq.enumerable.average(v=vs.90).aspx

I'd also expect Linq to start working well on iOS with the new IL2CPP engine that's practically required already for iOS.