Freely convert between List and IEnumerable

前端 未结 6 963
逝去的感伤
逝去的感伤 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:53

    To prevent duplication in memory, resharper is suggesting this:

    List myList = new List();
    IEnumerable myEnumerable = myList;
    List listAgain = myList as List() ?? myEnumerable.ToList();
    

    .ToList() returns a new immutable list. So changes to listAgain does not effect myList in @Tamas Czinege answer. This is correct in most instances for least two reasons: This helps prevent changes in one area effecting the other area (loose coupling), and it is very readable, since we shouldn't be designing code with compiler concerns.

    But there are certain instances, like being in a tight loop or working on an embedded or low memory system, where compiler considerations should be taken into consideration.

提交回复
热议问题