Sorting an IList in C#

前端 未结 15 2236
臣服心动
臣服心动 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<T>, 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<T> as you would a List<T>. 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<T> in place.
        public static void Sort<T>(this IList<T> list, Comparison<T> comparison)
        {
            ArrayList.Adapter((IList)list).Sort(new ComparisonComparer<T>(comparison));
        }
    
        // Sorts in IList<T> in place, when T is IComparable<T>
        public static void Sort<T>(this IList<T> list) where T: IComparable<T>
        {
            Comparison<T> comparison = (l, r) => l.CompareTo(r);
            Sort(list, comparison);
    
        }
    
        // Convenience method on IEnumerable<T> to allow passing of a
        // Comparison<T> delegate to the OrderBy method.
        public static IEnumerable<T> OrderBy<T>(this IEnumerable<T> list, Comparison<T> comparison)
        {
            return list.OrderBy(t => t, new ComparisonComparer<T>(comparison));
        }
    }
    
    // Wraps a generic Comparison<T> delegate in an IComparer to make it easy
    // to use a lambda expression for methods that take an IComparer or IComparer<T>
    public class ComparisonComparer<T> : IComparer<T>, IComparer
    {
        private readonly Comparison<T> _comparison;
    
        public ComparisonComparer(Comparison<T> 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<string> 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<string> 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/

    0 讨论(0)
  • 2020-11-28 07:10
    try this  **USE ORDER BY** :
    
       public class Employee
        {
            public string Id { get; set; }
            public string Name { get; set; }
        }
    
     private static IList<Employee> GetItems()
            {
                List<Employee> lst = new List<Employee>();
    
                lst.Add(new Employee { Id = "1", Name = "Emp1" });
                lst.Add(new Employee { Id = "2", Name = "Emp2" });
                lst.Add(new Employee { Id = "7", Name = "Emp7" });
                lst.Add(new Employee { Id = "4", Name = "Emp4" });
                lst.Add(new Employee { Id = "5", Name = "Emp5" });
                lst.Add(new Employee { Id = "6", Name = "Emp6" });
                lst.Add(new Employee { Id = "3", Name = "Emp3" });
    
                return lst;
            }
    
    **var lst = GetItems().AsEnumerable();
    
                var orderedLst = lst.OrderBy(t => t.Id).ToList();
    
                orderedLst.ForEach(emp => Console.WriteLine("Id - {0} Name -{1}", emp.Id, emp.Name));**
    
    0 讨论(0)
  • 2020-11-28 07:10

    Here's an example using the stronger typing. Not sure if it's necessarily the best way though.

    static void Main(string[] args)
    {
        IList list = new List<int>() { 1, 3, 2, 5, 4, 6, 9, 8, 7 };
        List<int> stronglyTypedList = new List<int>(Cast<int>(list));
        stronglyTypedList.Sort();
    }
    
    private static IEnumerable<T> Cast<T>(IEnumerable list)
    {
        foreach (T item in list)
        {
            yield return item;
        }
    }
    

    The Cast function is just a reimplementation of the extension method that comes with 3.5 written as a normal static method. It is quite ugly and verbose unfortunately.

    0 讨论(0)
提交回复
热议问题