C#: Getting maximum and minimum values of arbitrary properties of all items in a list

前端 未结 8 1732
温柔的废话
温柔的废话 2021-02-02 13:19

I have a specialized list that holds items of type IThing:

public class ThingList : IList
{...}

public interface IThing
{
    Decimal         


        
8条回答
  •  南旧
    南旧 (楼主)
    2021-02-02 13:55

    If using .NET 3.5, why not use lambdas?

    public Decimal GetMaximum(Func prop) {
        Decimal result = Decimal.MinValue;
        foreach (IThing thing in this)
            result = Math.Max(result, prop(thing));
    
        return result;
    }
    

    Usage:

    Decimal result = list.GetMaximum(x => x.Weight);
    

    This is strongly typed and efficient. There are also extension methods that already do exactly this.

提交回复
热议问题