.NET Why does IEnumerable.ToList () in an existing list create a new array

Just out of curiosity, why does calling IEnumerable.ToList () in an existing List not return the same instance? The same goes for IEnuerable.ToArray (). Isn't that better in terms of memory consumption?

I checked the following quick test:

var things= new List<Thing>( new [] {new Thing(), new Thing()}); Console.WriteLine(things.GetHashCode()); things= things.ToList(); Console.WriteLine(things.GetHashCode()); 

And I get different instances of objects. Why not just the same specimens?

+7
source share
3 answers

This is intentionally done to include the Copy List scenario.

For example, I do foreach( var a in list ) list.Remove(a) , I get an exception saying that the "collection was changed" when the listing was performed.

To fix this, I do: foreach( var a in list.ToList() ) list.Remove(a) .

If you need semantics along the lines of "convert to list, if it is not already one", you will have to process it yourself. In fact, you could write a neat extension method for this:

 public static IList<T> ToListIfNotAlready( this IEnumerable<T> source ) { var list = source as IList<T>; return list == null ? source.ToList() : list; } 

Yes, it could be the other way around, but LINQ designers chose this approach and had every right to do so, since no approach has a clear advantage in the general case.

+9
source

Since you cannot change the contents of an enumeration during an enumeration, sometimes you need to create a copy of the list so that you can iterate over one copy and modify another. ToList () is defined as returning a new list that is independent of the original list.

+1
source

The behavior of ToList () has nothing to do with enumeration. He does what the name implies, that is, returns a list. This does not mean that it returns the same list with every call; otherwise; copy of the list must be saved somewhere. Same thing with many other Linq features. The fact that it returns a new list is useful for use with the foreach enumerator.

0
source

All Articles