Sorting an IList in C#

前端 未结 15 2382
臣服心动
臣服心动 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

    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() { 1, 3, 2, 5, 4, 6, 9, 8, 7 };
        List stronglyTypedList = new List(Cast(list));
        stronglyTypedList.Sort();
    }
    
    private static IEnumerable Cast(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.

提交回复
热议问题