Eric Snyder
Eric Snyder

Reputation: 1924

Linq getting average on a property of a List<class>

I have a List. Coordinate has X, Y and Z that are double properties. I need to calculate the average of X, the average of Y and the average of Z.

   public class Coordinate
{
    public double X { get; set; }
    public double Y { get; set; }
    public double Z { get; set; }
}

Every example I can see is returning the average of a Collection or List of a simple double. How would the average of a property of a List be returned?

Upvotes: 2

Views: 1018

Answers (1)

Ashkan Mobayen Khiabani
Ashkan Mobayen Khiabani

Reputation: 34160

If you want the average of each pont X,Y,Z in a list you can do it like this:

List<double> Averages = Coordinates.Select(c=> (c.X + c.Y + c.Z)/3).ToList();

If you want a single coordinate that its X is the average of X'es and ... then:

Coordinate cordinate = new Coordinate
{
     X = Coordinates.Average(c => c.X),
     Y = Coordinates.Average(c => c.Y),
     Z = Coordinates.Average(c => c.Z)
};

Upvotes: 6

Related Questions