Search code examples
c++-cli

Finding max in generic list directly


I have a generic C++ CLI list which is populated with integers. I want to find the max value. Normally the list is sorted in ascending order. So I could just take the last item. Or I could sort the list and then take the last item but is there a way to avoid that and just do something like ->Max()?

         System::Collections::Generic::List<System::Int32>^ Testlist = gcnew System::Collections::Generic::List<System::Int32>();
         Testlist->Add(1);
         Testlist->Add(2);
         Testlist->Add(3);
         Testlist->Add(4);
         int max = Testlist[Testlist->Count-1];//too iffy..without having to sort, can I get max?

Solution

  • Call the Linq method to find the Max of an IEnumerable.

    using namespace System::Linq;
    
    List<Int32>^ list = ...;
    Int32 max = Enumerable::Max(list);
    

    C++/CLI doesn't support the fancy Linq query syntax, nor extension methods, but all extension methods are just static methods, and you can call that directly. (In C#, we could use the extension method to write list.Max().)