我想写的是
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/