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

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

    For C# 2.0 and .Net 2.0 you can do the following for Max:

    public delegate Decimal GetProperty(TElement element);
    
    public static Decimal Max(IEnumerable enumeration, 
                                        GetProperty getProperty)
    {
        Decimal max = Decimal.MinValue;
    
        foreach (TElement element in enumeration)
        {
            Decimal propertyValue = getProperty(element);
            max = Math.Max(max, propertyValue);
        }
    
        return max;
    }
    

    And here is how you would use it:

    string[] array = new string[] {"s","sss","ddsffffd","333","44432333"};
    
    Max(array, delegate(string e) { return e.Length;});
    

    Here is how you would do it with C# 3.0, .Net 3.5 and Linq, without the function above:

    string[] array = new string[] {"s","sss","ddsffffd","333","44432333"};
    array.Max( e => e.Length);
    

提交回复
热议问题