自定义排序,正序时将0排在最后。
2014-04-03 16:24 咒语 阅读(1170) 评论(0) 收藏 举报[Test]
public void OrderByDefinesTest()
{
var comper = new PositionComparer();
int[] ms = { 0, 0, 9, 34, 65 };
var os = ms.OrderBy(x => x, comper);
foreach (var i in os)
{
Console.WriteLine(i);
}
}
/// <summary>
/// 排序,0排最后
/// <remarks>x小于y时正序后x在前</remarks>
/// </summary>
class PositionComparer : IComparer<int>
{
public int Compare(int x, int y)
{
if (x == 0 && y > 0)
{
return 1;
}
if (x > 0 && y == 0)
{
return -1;
}
if (x > y)
{
return 1;
}
if (x < y)
{
return -1;
}
return 0;
}
}
浙公网安备 33010602011771号