直接在通用列表中查找最大值

Finding max in generic list directly

我有一个用整数填充的通用 C++ CLI 列表。我想找到最大值。通常,列表按升序排序。所以我可以拿最后一项。或者我可以对列表进行排序,然后取出最后一项,但有没有办法避免这种情况,只需执行 ->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?

调用 Linq 方法查找 IEnumerableMax

using namespace System::Linq;

List<Int32>^ list = ...;
Int32 max = Enumerable::Max(list);

C++/CLI 不支持花哨的 Linq 查询语法,也不支持扩展方法,但所有扩展方法都只是静态方法,您可以直接调用它。 (在C#中,我们可以使用扩展方法写成list.Max()。)