使用 C# 在通用列表中查找最高整数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1034282/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 06:37:35  来源:igfitidea点击:

Find highest integer in a Generic List using C#?

c#.net-3.5

提问by Michael Kniskern

I have the following List<int>collection and I need to find the highest integer in the collection. It could have an arbitrary number of integers and I can have same integer value for multiple times.

我有以下List<int>集合,我需要找到集合中的最大整数。它可以有任意数量的整数,我可以多次使用相同的整数值。

List<int> MyList = new List<int> { 3, 4, 6, 7, 9, 3, 4, 5, 5 };

What is the simplest algorithm to use for finding the highest integer? I am using C# and the .NET 3.5 framework.

用于查找最高整数的最简单算法是什么?我正在使用 C# 和 .NET 3.5 框架。

采纳答案by Reed Copsey

You can just do:

你可以这样做:

int max = MyList.Max();

See Enumerable.Maxfor details.

有关详细信息,请参阅Enumerable.Max

回答by Timothy Carter

Enumerable has a Maxfunction that will do this.

Enumerable 有一个Max函数可以做到这一点。

Looking at the implementation for the integer specific methodusing Reflector, the method loops through each element in the the IEnumerable source and compares it with what was previously the highest value.

查看使用 Reflector的整数特定方法的实现,该方法循环遍历 IEnumerable 源中的每个元素,并将其与以前的最高值进行比较。

回答by Dirk Vollmar

If you need to retrieve the maximum value frequently you might think about creating your own list class (or derive from List) which keeps the maximum item in a cache. Such a class could look like this:

如果您需要经常检索最大值,您可能会考虑创建自己的列表类(或从 List 派生),将最大项保存在缓存中。这样的类可能如下所示:

public class MaxList<T> : IList<T>, ICollection<T>, IEnumerable<T>
{
    T Maximum { get; set; }
    List<T> _list;

    public T this[int index] { get; set; }

    public void Add(T item)
    {
        if (item > this.Maximum)
        {
            this.Maximum = item;
        }
        _list.Add(item);
    }

    // ... IEnumerable<T>, ICollection<T> and IList<T> members 

}

Alternatively, you could derive from List directly and overwrite the Add and Remove methods (basically all methods modifying list items) and update the cache accordingly.

或者,您可以直接从 List 派生并覆盖 Add 和 Remove 方法(基本上所有修改列表项的方法)并相应地更新缓存。

If such an approach is really a benefit depends on your scenario. IT definitely is if you have a very large list with is rarely updated and you need to retrieve the maximum frequently. Otherwise go for the solutions already suggested because they are much simpler.

这种方法是否真的有好处取决于您的情况。如果您有一个很少更新的非常大的列表,并且您需要经常检索最大值,则绝对是这样。否则,请选择已经建议的解决方案,因为它们要简单得多。

回答by Jake

genericlist.Remove(genericlist.Max)

genericlist.Remove(genericlist.Max)