我有一个对象列表,其中一些可以为null.我希望它按一些属性排序,nulls在列表的末尾.然而,无论比较器返回什么,List<T>.Sort()方法似乎都将nulls放在开头.这是我用来测试这个的一个小程序:
class Program
{
class Foo {
public int Bar;
public Foo(int bar)
{
Bar = bar;
}
}
static void Main(string[] args)
{
List<Foo> list = new List<Foo>{null, new Foo(1), new Foo(3), null, new Foo(100)};
foreach (var foo in list)
{
Console.WriteLine("Foo: {0}", foo==null?"NULL":foo.Bar.ToString());
}
Console.WriteLine("Sorting:");
list.Sort(new Comparer());
foreach (var foo in list)
{
Console.WriteLine("Foo: {0}", foo == null ? "NULL" : foo.Bar.ToString());
}
Console.ReadKey();
}
class Comparer:IComparer<Foo>
{
#region Implementation of IComparer<in Foo>
public int Compare(Foo x, Foo y)
{
int xbar = x == null ? int.MinValue : x.Bar;
int ybar = y == null ? int.MinValue : y.Bar;
return ybar - xbar;
}
#endregion
}
}
Run Code Online (Sandbox Code Playgroud)
自己尝试一下:排序列表打印为
Foo: NULL
Foo: NULL
Foo: 100
Foo: 3
Foo: 1
Run Code Online (Sandbox Code Playgroud)
nulls首先,即使它们被比作int.Minvalue.这个方法是错误还是什么?
Eri*_*ert 13
您的实现不正确,因为您未能首先编写规范,然后编写符合规范的代码.
所以,重新开始.写一个规格:
现在你可以编写保证符合规范的代码:
// FooCompare takes two references to Foo, x and y. Either may be null.
// +1 means x is larger, -1 means y is larger, 0 means they are the same.
int FooCompare(Foo x, Foo y)
{
// if x and y are both null, they are equal.
if (x == null && y == null) return 0;
// if one is null and the other one is not then the non-null one is larger.
if (x != null && y == null) return 1;
if (y != null && x == null) return -1;
// if neither are null then the comparison is
// based on the value of the Bar property.
var xbar = x.Bar; // only calculate x.Bar once
var ybar = y.Bar; // only calculate y.Bar once
if (xbar > ybar) return 1;
if (ybar > xbar) return -1;
return 0;
}
// The original poster evidently wishes the list to be sorted from
// largest to smallest, where null is the smallest.
// Reverse the polarity of the neutron flow:
int Compare(Foo x, Foo y)
{
return FooCompare(y, x);
}
Run Code Online (Sandbox Code Playgroud)
不要搞乱巧妙的整数运算技巧; 正如你所见,聪明的等于越野车.首先是正确的.
Kon*_*lph 12
让我们说x是null和y是1.
int xbar = x == null ? int.MinValue : x.Bar;
int ybar = y == null ? int.MinValue : y.Bar;
return ybar - xbar;
Run Code Online (Sandbox Code Playgroud)
所以现在我们有了1 - int.MinValue.这将是溢出,因此最终结果将为负,因此null将被视为小于1.
出于这个原因,计算从根本上是有缺陷的.
public int Compare(Foo x, Foo y)
{
int xbar = x == null ? int.MinValue : x.Bar;
int ybar = y == null ? int.MinValue : y.Bar;
return ybar.CompareTo(xbar);
}
Run Code Online (Sandbox Code Playgroud)
(感谢评论者指出我方法中的缺陷.)