SortedList
そのデータをソートするためだけに一連の値を に追加するのはかなり非効率的です。O(n ^ 2)である「挿入ソート」を効果的に実行しています。最も広く使用されているソート アルゴリズムは O(n*log(n)) です。
その上、最大値だけが必要な場合は、データを 1 回だけループして、O(1) 時間で最大値を計算できます。
Max 値を見つけるには、単純に LINQ のMax
関数を使用します。
IEnumerable<X> data = ...;
float max = data.Max(item => doSomeComputation(item));
最大値を生成する項目を取得するには、MaxBy を使用できます。(残念ながら、.NET には直接出荷されていないため、自分で作成/追加する必要があります。)
X maxItem = data.MaxBy(item => doSomeComputation(item));
public static TSource MaxBy<TSource, TKey>(this IEnumerable<TSource> source
, Func<TSource, TKey> selector
, IComparer<TKey> comparer = null)
{
if (comparer == null)
{
comparer = Comparer<TKey>.Default;
}
using (IEnumerator<TSource> iterator = source.GetEnumerator())
{
if (!iterator.MoveNext())
{
throw new ArgumentException("Source was empty");
}
TSource maxItem = iterator.Current;
TKey maxValue = selector(maxItem);
while (iterator.MoveNext())
{
TKey nextValue = selector(iterator.Current);
if (comparer.Compare(nextValue, maxValue) > 0)
{
maxValue = nextValue;
maxItem = iterator.Current;
}
}
return maxItem;
}
}