Sorting an IList in C#

前端 未结 15 2388
臣服心动
臣服心动 2020-11-28 06:36

So I came across an interesting problem today. We have a WCF web service that returns an IList. Not really a big deal until I wanted to sort it.

Turns out the IList

15条回答
  •  一个人的身影
    2020-11-28 07:10

    This question inspired me to write a blog post: http://blog.velir.com/index.php/2011/02/17/ilistt-sorting-a-better-way/

    I think that, ideally, the .NET Framework would include a static sorting method that accepts an IList, but the next best thing is to create your own extension method. It's not too hard to create a couple of methods that will allow you to sort an IList as you would a List. As a bonus you can overload the LINQ OrderBy extension method using the same technique, so that whether you're using List.Sort, IList.Sort, or IEnumerable.OrderBy, you can use the exact same syntax.

    public static class SortExtensions
    {
        //  Sorts an IList in place.
        public static void Sort(this IList list, Comparison comparison)
        {
            ArrayList.Adapter((IList)list).Sort(new ComparisonComparer(comparison));
        }
    
        // Sorts in IList in place, when T is IComparable
        public static void Sort(this IList list) where T: IComparable
        {
            Comparison comparison = (l, r) => l.CompareTo(r);
            Sort(list, comparison);
    
        }
    
        // Convenience method on IEnumerable to allow passing of a
        // Comparison delegate to the OrderBy method.
        public static IEnumerable OrderBy(this IEnumerable list, Comparison comparison)
        {
            return list.OrderBy(t => t, new ComparisonComparer(comparison));
        }
    }
    
    // Wraps a generic Comparison delegate in an IComparer to make it easy
    // to use a lambda expression for methods that take an IComparer or IComparer
    public class ComparisonComparer : IComparer, IComparer
    {
        private readonly Comparison _comparison;
    
        public ComparisonComparer(Comparison comparison)
        {
            _comparison = comparison;
        }
    
        public int Compare(T x, T y)
        {
            return _comparison(x, y);
        }
    
        public int Compare(object o1, object o2)
        {
            return _comparison((T)o1, (T)o2);
        }
    }
    

    With these extensions, sort your IList just like you would a List:

    IList iList = new []
    {
        "Carlton", "Alison", "Bob", "Eric", "David"
    };
    
    // Use the custom extensions:
    
    // Sort in-place, by string length
    iList.Sort((s1, s2) => s1.Length.CompareTo(s2.Length));
    
    // Or use OrderBy()
    IEnumerable ordered = iList.OrderBy((s1, s2) => s1.Length.CompareTo(s2.Length));
    

    There's more info in the post: http://blog.velir.com/index.php/2011/02/17/ilistt-sorting-a-better-way/

提交回复
热议问题