c# - 类定义自定义排序顺序

标签 c# list sorting

我有很多简单的类需要排序。示例:

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/

相关文章:

java - 从 map 中查找前 100 个元素的最有效方法

c# - 如何在 C# 中将 SVG 文件转换为 EMF 文件

JAVA迭代并将对象从一个列表复制到另一个列表

list - Erlang 记录项列表

qt - 使用 sortItems() 对 QListWidget 进行排序

Java PriorityQueue Comparator 在特定条件下插入二维数组

c# - 多次关闭和 ReSharper 的 "Access to Modified Closure"警告

c# - 返回包含相同对象的列表

c# - 类总是尝试在设计 View 中打开,而不是代码 View

android - 测量渲染 ListView 的时间