如何对列表<>进行排序

本文关键字:排序 列表 | 更新日期: 2023-09-27 18:06:12

可能的重复项:
对自定义类列表进行排序<>

我有一个通用收集器List和一些代码以无序方式向收集器添加CmsCategoryCmsCategory有字段int CategoryIdstring Title

List<CmsCategory> categories = new List<CmsCategory>();
categories.Sort();

插入完成后,我需要按CategoryId (ascending)对收集器中的所有对象进行排序。

我收到此错误:

至少有一个对象必须实现 IComparable。

我的问题:

  • 我在这里用List<T>做错了什么?

  • 您是否知道更适合此类操作的通用收集器?

感谢您抽出宝贵时间。

如何对列表<>进行排序

可以使用

OrderBy() 方法根据属性进行排序:

var sortedItems = categories.OrderBy(x => x.CategoryId);

如果需要列表中的项目,可以调用.ToList()

var sortedList = sortedItems.ToList();

使用 OrderBy() 很酷的事情是,您还可以将ThenBy()与它一起使用,以基于第二个(或第三个,或第四个...(属性进行排序:

var reallySortedItems = categories.OrderBy(x => x.CategoryId).ThenBy(x => x.OtherProp);

自定义类型需要实现 IComparable 接口。

class CmsCategory: IComparable<CategoryID>
{
     public int CategoryID { get; set; }
     #region IComparable<CmsCategory> Members
     public int CompareTo( CmsCategory other )
     {
         if ( this.CategoryID < other.CategoryID ) return 1;
         else if ( this.CategoryID > other.CategoryID ) return -1;
         else return 0;
     }
     #endregion
}

或者,如果需要在不同情况下对对象的不同属性进行排序,则可以创建适当的 IComparer 实现,并将这些实现传递到 sort 方法中。

class CmsCategory_SortByName : IComparer<CmsCategory>
{
    #region IComparer<CmsCategory> Members
    public int Compare( CmsCategory x, CmsCategory y )
    {
        return string.Compare( x.Name, y.Name );
    }
    #endregion
}
var customSort = new CmsCategory_SortByName();
categories.Sort(customSort);

你可以像这样使用 Linq:

List<CmsCategory> categories = new List<CmsCategory>();
categories = categories.OrderBy(c => c.CategoryId).ToList();

对于更复杂的方案,您可以使用比较:

internal class CmsCategoryComparison
{
   public static int Compare(CmsCategory a, CmsCategory b)
   {
      // return either -1, 0, 1 like the CompareTo() method would
   }
}
List<CmsCategory> categories = new List<CmsCategory>();
categories.Sort(CmsCategoryComparison.Compare);

尝试:

categories.OrderBy(x=>x.CategoryId);

有 3 种简单的方法可以做到这一点。

使用委托

class Book
{
    public Book(string id, string name, string author)
    {
        ID = id;
        Name = name;
        Author = author;
    }
    public string ID { get; set; }
    public string Name { get; set; }
    public string Author { get; set; }
}
List<Book> listBook = new List<Book>();
        listBook.Add(new Book( "103", "Code Complete", "Steve MC"  ));
        listBook.Add(new Book("101", "Effective C++", "Scott Meyers"));
        listBook.Add(new Book("102", "CLR Via C#", "Jeff Prosise"));
        listBook.Sort(
            delegate(Book a, Book b) 
            {
                return a.ID.CompareTo(b.ID);
            });

使用比较器

    static int CompareBook(Book a, Book b)
    {
        return a.ID.CompareTo(b.ID);
    }
        listBook.Sort( CompareBook );

使用 IComparable

class Book : IComparable
{
    public Book(string id, string name, string author)
    {
        ID = id;
        Name = name;
        Author = author;
    }
    public string ID { get; set; }
    public string Name { get; set; }
    public string Author { get; set; }
    public int CompareTo(object obj)
    {
        return ID.CompareTo(((Book)obj).ID);
    }
}

最后,这是你的选择!:)

您可以让 CmsCategory 继承 IComparable,也可以使用另一个接受 Compare(T( 委托的 Sort 重载。

最后一种情况可能如下所示:

categories.Sort( (x,y) => { 
 if(x.CategoryId > y.CategoryId)
  return 1;
 else if(x.CategoryId == y.CategoryId)
  return 0;
 else
  return -1;
});

你必须提供比较功能

CmsCategory.compareTo(CmsCategory(

能够为您的 CmsCategory 元素提供总排序。

只需按照编译器的建议进行操作:如果要使用该 Sort 方法进行排序,请将该接口实现到 CsmCategory 类中。

您需要在CmsCategory中实现IComparable<T>

class CmsCategory : IComparable<CmsCategory>
{
    public int CompareTo(CmsCategory other)
    {
        return this.CategoryId.CompareTo(other.CategoryId);
    }
}

然后,您将能够执行就地排序:

List<CmsCategory> list = new List<CmsCategory> { new CmsCategory(), new CmsCategory() };
list.Sort();