Freely convert between List and IEnumerable

前端 未结 6 967
逝去的感伤
逝去的感伤 2020-12-04 08:21

How can I convert a List to an IEnumerable and then back again?

I want to do this in order to run a series

6条回答
  •  醉话见心
    2020-12-04 08:51

    Aside: Note that the standard LINQ operators (as per the earlier example) don't change the existing list - list.OrderBy(...).ToList() will create a new list based on the re-ordered sequence. It is pretty easy, however, to create an extension method that allows you to use lambdas with List.Sort:

    static void Sort(this List list,
        Func selector)
    {
        var comparer = Comparer.Default;
        list.Sort((x,y) => comparer.Compare(selector(x), selector(y)));
    }
    
    static void SortDescending(this List list,
        Func selector)
    {
        var comparer = Comparer.Default;
        list.Sort((x,y) => comparer.Compare(selector(y), selector(x)));
    }
    

    Then you can use:

    list.Sort(x=>x.SomeProp); // etc
    

    This updates the existing list in the same way that List.Sort usually does.

提交回复
热议问题