Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List order changes after modifying a property

Tags:

c#

list

lambda

linq

I have the following code:

                // Order a list
                var orderedList = myList.OrderBy(x => x.name);

                // Take few elements to another list (copies as reference)
                List<GameObject> myList2 = orderedList.Where(x => x.z == y).ToList();

                // Rename the objects in myList2
                foreach(stuff in myList2)
                {
                    stuff.name = "Renamed";
                }

The question is why after modifying a property of an object in the myList2 changes the order of orderedList?

For example if the ordered list was "a,b,c,d" and I took the "b" and "c" to myList2. Then the orderedList would be "a,d,Renamed,Renamed" instead of "a,Renamed, Renamed, d".

like image 739
Esa Avatar asked Feb 01 '26 00:02

Esa


1 Answers

Because orderedList is not a list, but a query.

Everytime you iterate over orderedList, OrderBy is invoked again. This is called deferred execution.


You can stop that behaviour by materializing the query, like

var orderedList = myList.OrderBy(x => x.name).ToList();

This way, changing the elements in orderedList will not actually changed the ordering of the items inside orderedList.

If myList is already a List<>, you could of course sort the list in-place instead of creating another one, like

// Order a list; don't create a new one
myList.Sort((a, b) => a.name.CompareTo(b.name));
like image 75
sloth Avatar answered Feb 02 '26 12:02

sloth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!