c# - 有没有办法使用自定义 OrderBy 或 Min 而无需实现 IComparer<T> ?

标签 c# .net linq

我想写的是

        return possibilities.OrderBy((x, y) =>
            {
                // returns true or false depending on whether x is 
                // lexographically smaller than y, e.g. x={1,2,3} 
                // is lexographically smaller than y={1,3,2}
                for(int i = 0; i < x.Length; ++i)
                {
                    if(x[i] < y[i])
                        return true;
                    else if(x[i] > y[i])
                        return false;
                }
                return true;
            })
            .First();

哪里possibilities类型为IEnumerable<int[]> 。然而,令我惊讶的是,这种语法无效,并且我通过谷歌搜索找到的所有内容都表明我必须编写一堆额外的代码来实现 IComparer<int[]> 。真的吗?

最佳答案

Comparer<T>.Create(Comparison<T>) 可以在.NET 4.5或更高版本中使用:

IEnumerable<int[]> a = new[] { new []{ 1, 2 }, new[] { 3, 4 } };

int[] min = a.OrderBy(x => x, Comparer<int[]>.Create((x, y) => {
    for (int z, i = 0; i < x.Length; i++)
        if ((z = x[i] - y[i]) != 0) return z;
    return 0;
})).FirstOrDefault();

但这并不需要找到最小值:

int[] min = a.Aggregate((x, y) => {
    for (int i = 0; i < x.Length; ++i) {
        if (x[i] < y[i]) return x;
        if (x[i] > y[i]) return y;
    }
    return x;
});

关于c# - 有没有办法使用自定义 OrderBy 或 Min 而无需实现 IComparer<T> ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42600693/

相关文章:

c# - 哪个线程最先进入临界区?

c# - 是否有机会使用 Linq (C#) 获得唯一记录?

c# - 使用 lambda 对列表进行排序和子排序

c# - 替换.net core中webhost使用的servicecollection中的一个服务

.net - 在 Powershell 中使用 .NET 属性

c# - 在 LINQ 查询中将正 bool 结果与 true 和 false 进行比较

c# - 如何使用 LINQ C# 根据多个条件更新列表

c# - 如果文件夹中没有某些 dll,则无法运行工具包?/

c# - ASP.NET初学者问题: How do I implement something like this is my ASP. NET C#网站?

c# - P/Invoke & InterOP 中是否有用于编码的匹配类型表?