Reputation: 179
Does this create memory leaks if used in cycles?
mylist = mylist.Distinct().ToList();
If so, whats a good approach for lists if you only need to update it(particularly with LINQ), not to create a new one?
Upvotes: 1
Views: 182
Reputation: 13778
The cited line of code:
mylist = mylist.Distinct().ToList();
will create a new object of type List<T>
, where T
is typeof(mylist)
.
The list will contain references to a subset (possibly all, or none) of the original objects in mylist
, as returned by the Distinct()
LINQ operator.
Therefore, the situation you have after that line of code is that you have the original list, all of the original objects that were in the original list, plus a new list that references some subset of the original objects.
So yes, you've used a bit more memory (but not much, relatively speaking).
That in itself is not a memory leak. That would depend what you now do with your new list. If you simply set it to null, or it goes out of scope, then it will normally be garbage collected (eventually) and you'll get all the memory back; no leak. However, if you do something that causes another object to hold a reference to your list, then you could potentially have a memory leak.
Some ways that you could unknowingly be holding a reference to your new list include:
Upvotes: 1