Finding minimum values of (properties of ) collections in C#

Dave picture Dave · Sep 30, 2010 · Viewed 7.3k times · Source

Given the following code from a Microsoft example:

public class EngineMeasurementCollection : Collection<EngineMeasurement>
{
    public EngineMeasurementCollection()
    {
        Add(new EngineMeasurement { Speed = 1000, Torque = 100, Power = 20 });
        Add(new EngineMeasurement { Speed = 2000, Torque = 160, Power = 60 });
        Add(new EngineMeasurement { Speed = 3000, Torque = 210, Power = 125 });
        Add(new EngineMeasurement { Speed = 4000, Torque = 220, Power = 160 });
        Add(new EngineMeasurement { Speed = 5000, Torque = 215, Power = 205 });
        Add(new EngineMeasurement { Speed = 6000, Torque = 200, Power = 225 });
        Add(new EngineMeasurement { Speed = 7000, Torque = 170, Power = 200 });
    }
}
public class EngineMeasurement
{
    public int Speed { get; set; }
    public int Torque { get; set; }
    public int Power { get; set; }
}

How do I get the minimum/maximum of Speed or Torque or Power. I need this to set the scale on a chart I'm doing (WPF Toolkit Chart to be precise). I suppose I could have a method inside EngineMeasurementCollection that iterates through each EngineMeasurement and looks at Power (or Speed), but I suspect there is a much easier way? The class Collection does have some sort of Min method, but note, I'm not trying to get the minimum of the collection (I'm not sure what that would mean in this case) but rather, the minimum of a particular property (ex. Speed). I did see the use of Collection.Min with functors. Is there something that could be done there? Or with Linq? I'm interested in all ways. Thanks, Dave

Bonus question (perhaps this will be obvious to me with the answer to min/max). What are the options to decide if a value (such as Speed is already in the collection). It's not clear from this example, but it could be the case that if you already have some data for a given independent variable (time for example), you don't want any more. So is there something like Collection.Contains("specify property you are interested in")?

Answer

Dan Abramov picture Dan Abramov · Sep 30, 2010
using System.Linq;

var collection = new EngineMeasurementCollection();
int maxSpeed = collection.Max(em => em.Speed);

See also:
LINQ MSDN documentation
LINQ to Objects 5 Minute Overview