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

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

    (Edited to reflect .NET 2.0 answer, and LINQBridge in VS2005...)

    There are three situations here - although the OP only has .NET 2.0, other people facing the same problem may not...

    1) Using .NET 3.5 and C# 3.0: use LINQ to Objects like this:

    decimal maxWeight = list.Max(thing => thing.Weight);
    decimal minWeight = list.Min(thing => thing.Weight);
    

    2) Using .NET 2.0 and C# 3.0: use LINQBridge and the same code

    3) Using .NET 2.0 and C# 2.0: use LINQBridge and anonymous methods:

    decimal maxWeight = Enumerable.Max(list, delegate(IThing thing) 
        { return thing.Weight; }
    );
    decimal minWeight = Enumerable.Min(list, delegate(IThing thing)
        { return thing.Weight; }
    );
    

    (I don't have a C# 2.0 compiler to hand to test the above - if it complains about an ambiguous conversion, cast the delegate to Func.)

    LINQBridge will work with VS2005, but you don't get extension methods, lambda expressions, query expressions etc. Clearly migrating to C# 3 is a nicer option, but I'd prefer using LINQBridge to implementing the same functionality myself.

    All of these suggestions involve walking the list twice if you need to get both the max and min. If you've got a situation where you're loading from disk lazily or something like that, and you want to calculate several aggregates in one go, you might want to look at my "Push LINQ" code in MiscUtil. (That works with .NET 2.0 as well.)

提交回复
热议问题