我有一个对象列表,其中一些可以为null.我希望它按一些属性排序,列表末尾有空值.但是,无论比较器返回什么,List< T> .sort()方法似乎都会在开头放置空值.这是我用来测试这个的一个小程序:
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 } }
自己尝试一下:排序列表打印为
Foo: NULL Foo: NULL Foo: 100 Foo: 3 Foo: 1
解决方法
假设x为null且y为1.
int xbar = x == null ? int.MinValue : x.Bar; int ybar = y == null ? int.MinValue : y.Bar; return ybar - xbar;
所以现在我们有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); }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。