什么是排序一个IList&LT的最佳途径; T>在NET 2.0?

什么是排序一个IList&LT的最佳途径; T>在NET 2.0?

问题描述:

我有一个的IList< T> ,我需要进行排序,如果可能的话,我宁愿不要复制列表。我注意到的ArrayList 有一个包裹传递的列表中没有复制它的适配器静态方法,但这需要一个的IList 和我有一个的IList< T> 。它是安全的投从 System.Collections.Generic.IList< T> System.Collections.IList 而仅仅使用适配器的方法?

I have an IList<T> that I need to sort, and I would rather not copy the list if possible. I've noticed that ArrayList has an Adapter static method that wraps the passed list without copying it, but this takes an IList and I have an IList<T>. Is it safe to cast from a System.Collections.Generic.IList<T> to a System.Collections.IList and just use the Adapter method?

请注意,这是NET 2.0,所以LINQ不是一个选项。

Note that this is .Net 2.0, so LINQ is not an option.

从保罗·福克斯的博客,我推荐了帖子如何排序一个IList:的 http://foxsys.blogspot.com/2007/06/how-to-sort-generic-ilist.html 一>

From the blog of Paul Fox, I recommend the post "How to sort an IList": http://foxsys.blogspot.com/2007/06/how-to-sort-generic-ilist.html

以防万一的博客消失,在未来,我会在这里复制后:

Just in case that blog goes away in the future, I'll copy the post here:


如何排序的一个通用的IList

更新

您可以读取和有关的分类通用的IList和列表。很多人会preFER在更新的帖子中提到的方法。

You can read and updated post about sorting generic IList and List. Many people will prefer the methods mentioned in the updated post.

排序一个通用的IList

Sorting a generic IList

我试图整理一个通用的IList&LT;>,发现这样做的一个相当简单的方式

I was trying to sort a generic IList<> and found a fairly simple way of doing it.

第1步

您需要实现IComparable包含在你的IList的类型。在这个例子中,我将使用一个简单的语言DTO类。

You need to implement IComparable for the type contained in your IList. For this example I am going to use a simple Language Dto class.

public class LanguageDto : IComparable {
 private String name;
 public string Name { get { return name; } set { name = value; } }

 public LanguageDto(string name) {
     this.name = name;
 }

 #region IComparable Members
 public int CompareTo(object obj) {
     if (obj is LanguageDto) {
     LanguageDto language = (LanguageDto)obj;
     return this.name.CompareTo(language.name);
     }
     throw new ArgumentException(string.Format("Cannot compare a LanguageDto to an {0}", obj.GetType().ToString()));
 }
 #endregion
}

第2步

排序您的IList。要做到这一点,你将使用ArrayList.Adapter()方法来传递您的IList中,然后调用排序方法。像这样...

Sort your IList. To do this you will use the ArrayList.Adapter() method passing in your IList, and then calling the Sort method. Like so...

ArrayList.Adapter((IList)languages).Sort();

请注意:语言的类型是IList的

Note: languages is of type "IList"

语言应该是你的类型的排序列表!

Languages should then be a sorted list of your type!