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

前端 未结 8 1599
温柔的废话
温柔的废话 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:54

    How about a generalised .Net 2 solution?

    public delegate A AggregateAction( A prevResult, B currentElement );
    
    public static Tagg Aggregate( 
        IEnumerable source, Tagg seed, AggregateAction func )
    {
        Tagg result = seed;
    
        foreach ( Tcoll element in source ) 
            result = func( result, element );
    
        return result;
    }
    
    //this makes max easy
    public static int Max( IEnumerable source )
    {
        return Aggregate( source, 0, 
            delegate( int prev, int curr ) { return curr > prev ? curr : prev; } );
    }
    
    //but you could also do sum
    public static int Sum( IEnumerable source )
    {
        return Aggregate( source, 0, 
            delegate( int prev, int curr ) { return curr + prev; } );
    }
    

提交回复
热议问题