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

前端 未结 8 1679
温柔的废话
温柔的废话 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 14:09

    Conclusion: There is no better way for .Net 2.0 (with Visual Studio 2005).

    You seem to have misunderstood the answers (especially Jon's). You can use option 3 from his answer. If you don't want to use LinqBridge you can still use a delegate and implement the Max method yourself, similar to the method I've posted:

    delegate Decimal PropertyValue(IThing thing);
    
    public class ThingList : IList {
        public Decimal Max(PropertyValue prop) {
            Decimal result = Decimal.MinValue;
            foreach (IThing thing in this) {
                result = Math.Max(result, prop(thing));
            }
            return result;
        }
    }
    

    Usage:

    ThingList lst;
    lst.Max(delegate(IThing thing) { return thing.Age; });
    

提交回复
热议问题