c# - 如何在不使用 OrderBy 的情况下从点数组中获取具有最小 X 的点?

标签 c# .net linq linq-to-objects

想象一下

 var points = new Point[]
 {
     new Point(1, 2),
     new Point(2, 3)
 };

为了得到我能用最小 X 的点:

 var result = points.OrderBy(point => point.X).First();

但对于大型阵列,我认为这不是更快的选择。有更快的选择吗?

最佳答案

更好用

int x = points.Min(p => p.X);
var result = points.First(p => p.X == x);

因为这消除了对该列表进行排序的必要性(即,它是 O(n) 而不是 O(n log n))。此外,它比使用 OrderByFirst 更清晰。

您甚至可以编写如下扩展方法:

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;
    }

用法:

IEnumerable<Point> points;
Point minPoint = points.SelectMin(p => p.X);

您可以概括您的需求。这样做的好处是它避免了两次遍历列表的可能性。

关于c# - 如何在不使用 OrderBy 的情况下从点数组中获取具有最小 X 的点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1574330/

相关文章:

c# - 调试 WCF 服务时出现问题

C# 国际奥委会 : Implementing conditional injection

LINQ 到 SQL -

c# - 从 DateTime 列中为每一天选择最小时间值

C# LINQ 按位置搜索

c# - 将新对象实例分配给绑定(bind)变量时数据绑定(bind)不起作用

c# - 我如何知道任务是因超时还是手动触发而取消?

c# - log4net - 使用 .config 文件部分(WebService/IIS)配置存储库 [MyProject] 时出错

c# - 如果每个 async 都有一个 await,并且每个 await 都应用于一个 async,那么它在哪里以及如何结束?

c# - 是否有 ClaimTypes 属性来表示 "city"?