我有很多简单的类需要排序。示例:
IEnumerable<Sortsample> OutputList = List.OrderBy(x => x);
所有的类只需要像这样按定义的属性排序:
class Sortsample
{
[SortAttribute] //Item should be sorted by Date
public DateTime Date { get; set; }
public string Name { get; set; }
}
是否有类似 [SortAttribute]
的东西(或类似的简单方法),或者我是否必须为每个类实现 CompareTo
?
最佳答案
我建议实现 IComparable<Sortsample>
:
class Sortsample: IComparable<Sortsample> {
public DateTime Date {
get; set;
}
public string Name {
get; set;
}
public int CompareTo(Sortsample other) {
// if "other" is, in fact, "this"
if (Object.ReferenceEquals(this, other))
return 0;
else if (Object.ReferenceEquals(null, other))
return 1; // let's consider that "this" (not null) > null
// other is not this, and other is not null
return Date.CompareTo(other.Date);
}
}
关于c# - 类定义自定义排序顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36740303/