Fast/efficient way to get index of minimum value in List<T>?

Is there any way to find minimum value index more efficient/faster than this?

int minimumValueIndex = List.IndexOf(List.Min());

Answers


Yes, you can remove the overhead of List.IndexOf() by building a custom Min() extension. (Really, Enumerable.Min() should have an extension that selects the original element by key instead of selecting a transformation. This oversight is particularly painful in situations like this.)

public static int IndexOfMin(this IList<int> self)
{
    if (self == null) {
        throw new ArgumentNullException("self");
    }

    if (self.Count == 0) {
        throw new ArgumentException("List is empty.", "self");
    }

    int min = self[0];
    int minIndex = 0;

    for (int i = 1; i < self.Count; ++i) {
        if (self[i] < min) {
            min = self[i];
            minIndex = i;
        }
    }

    return minIndex;
}

Need Your Help

Amazon EC2 and S3: How to read and write data

hadoop amazon-s3 amazon-ec2 hbase

I have just followed this guide: http://rogueleaderr.tumblr.com/post/32768181371/set-up-and-run-a-fully-distributed-hadoop-hbase-cluster to get a cluster set up on Amazon EC2 with hadoop and hbase

make widget set to home screen after install/first launch?

android eclipse android-widget widget shortcut

I have code to make a shortcut of my application on the home screen when the user firsts opens the application. Is it possible to make it so that the application sets it so that when the user opens...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.