我想对我在特定标准上的自定义列表进行排序。列表中的每一项都包含一个名为"Status“的属性,它是一个枚举,如下所示。
Empty = 0, Normal = 1, Aged = 2, Dead = 3 不能更改上面指定的值。当我对我的状态属性进行排序时,我希望订单是如此正常,衰老,空虚和死亡。我不知道该怎么做才好呢?
下面是一个用于处理不同排序问题的类的示例。不知道我会如何“转换”这个类来解决上面的问题?
public class SortOrders : IComparer<OrderBlocks.Order>
{
private bool _sortDescending;
public SortOrders(bool sortDescending)
{
this._sortDescending = sortDescending;
}
public SortOrders()
: this(false) // sort ascending by default
{
}
public int Compare(OrderBlocks.Order x, OrderBlocks.Order y)
{
if (this._sortDescending)
{
return y.StatusGood.CompareTo(x.StatusGood);
}
else
{
return x.StatusGood.CompareTo(y.StatusGood);
}
}
}发布于 2013-12-19 10:31:20
有很多方法可以使用OrderBy来实现
将OrderBy和ThenBy调用与您的定制订单链接在一起:
var ordered = list.OrderBy(f1 => f1.Status == 3)
.ThenBy(f2 => f2.Status == 0)
.ThenBy(f3 => f3.Status == 2)
.ThenBy(f4 => f4.Status == 1).ToList();或内联使用委托开关/大小写:
var ordered2 = list.OrderBy(foo =>
{
switch (foo.Status)
{
case (int)Status.Normal:
return 0;
case (int)Status.Aged:
return 1;
case (int)Status.Empty:
return 2;
case (int)Status.Dead:
return 3;
default:
return 0;
}
}).ToList();两者都给出了相同的结果。第一个方法使用您已经拥有的枚举值,第二个方法查看枚举值,并返回一个用于比较的不同整数。
发布于 2013-12-19 10:23:28
下面是我如何使用Linq来完成这个任务:
var sorted = myList.OrderBy(x =>
{
switch (x.Status)
{
case SomethingStatus.Normal:
return 0;
case SomethingStatus.Aged:
return 1;
case SomethingStatus.Empty:
return 2;
case SomethingStatus.Dead:
return 3;
default:
return 10;
}
});发布于 2013-12-19 10:20:52
我将创建一个转换函数,在进行比较之前,StatusGood将通过该转换函数,即:
public static class StatusGoodExtensions
{
public static int OrderIndex(this StatusGood statusIn)
{
switch ( statusIn )
{
case StatusGood.Normal: return 0;
case StatusGood.Aged: return 1;
case StatusGood.Empty: return 2;
case StatusGood.Dead: return 3;
}
throw new NotImplementedException(statusIn.ToString());
}
}用于比较,如下所示:
return x.StatusGood.OrderIndex().CompareTo(y.StatusGood.OrderIndex());通过使用扩展方法,返回顺序的逻辑与排序完全分离,并且可以在其他地方进行测试或重新使用。
https://stackoverflow.com/questions/20678671
复制相似问题