title: C#: Getting maximum and minimum values of arbitrary properties of all items in a list
body: <p>I have a specialized list that holds items of type <code>IThing</code>:</p>
  
  <pre><code>public class ThingList : IList&lt;IThing&gt;
  {...}
  
  public interface IThing
  {
      Decimal Weight { get; set; }
      Decimal Velocity { get; set; }
      Decimal Distance { get; set; }
      Decimal Age { get; set; }
      Decimal AnotherValue { get; set; }
  
      [...even more properties and methods...]
  }
  </code></pre>
  
  <p>Sometimes I need to know the maximum or minimum of a certain property of all the things in the list. Because of "Tell don't ask" we let the List figure it out:</p>
  
  <pre><code>public class ThingList : IList&lt;IThing&gt;
  {
      public Decimal GetMaximumWeight()
      {
          Decimal result = 0;
          foreach (IThing thing in this) {
              result = Math.Max(result, thing.Weight);
          }
          return result;
      }
  }
  </code></pre>
  
  <p>Thats very nice. But sometimes I need the minimum weight, sometimes the maximum velocity and so on. I don't want a <code>GetMaximum*()/GetMinimum*()</code> pair for every single property.</p>
  
  <p>One solution would be reflection. Something like (hold your nose, strong code smell!):</p>
  
  <pre><code>Decimal GetMaximum(String propertyName);
  Decimal GetMinimum(String propertyName);
  </code></pre>
  
  <p>Are there any better, less smelly ways to accomplish this?</p>
  
  <p>Thanks,
  Eric</p>
  
  <p>Edit: @Matt: .Net 2.0</p>
  
  <p><strike>Conclusion: There is no better way for .Net 2.0 (with Visual Studio 2005). Maybe we should move to .Net 3.5 and Visual Studio 2008 sometime soon. Thanks, guys.</strike></p>
  
  <p>Conclusion: There are diffent ways that are far better than reflection. Depending on runtime and C# version. Have a look at Jon Skeets answer for the differences. All answers are are very helpful.</p>
  
  <p>I will go for Sklivvz suggestion (anonymous methods). There are several code snippets from other people (Konrad Rudolph, Matt Hamilton and Coincoin) which implement Sklivvz idea. I can only "accept" one answer, unfortunately.</p>
  
  <p>Thank you very much. You can all feel "accepted", altough only Sklivvz gets the credits ;-)</p>