It is better to use
int x = points.Min(p => p.X);
var result = points.First(p => p.X == x);
as this eliminates the necessity of sorting this list (i.e., it is O(n)
as opposed to, say, O(n log n)
). Further, it's clearer than using OrderBy
and First
.
You could even write an extension method as follows:
static class IEnumerableExtensions {
public static T SelectMin<T>(this IEnumerable<T> source, Func<T, int> selector) {
if (source == null) {
throw new ArgumentNullException("source");
}
int min = 0;
T returnValue = default(T);
bool flag = false;
foreach (T t in source) {
int value = selector(t);
if (flag) {
if (value < min) {
returnValue = t;
min = value;
}
}
else {
min = value;
returnValue = t;
flag = true;
}
}
if (!flag) {
throw new InvalidOperationException("source is empty");
}
return returnValue;
}
Usage:
IEnumerable<Point> points;
Point minPoint = points.SelectMin(p => p.X);
You can generalize to your needs. The advantage of this is that it avoids potentially walking the list twice.