2

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".

Esa
  • 1,636
  • 3
  • 19
  • 23

1 Answers1

6

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));
Community
  • 1
  • 1
sloth
  • 99,095
  • 21
  • 171
  • 219
  • In my case order of the list is changing seldom for same parameters. I am wondering why? Order should be same each time a piece of code is executed for same inputs in my linq where clause? Or is there any thing special they way items are sort when using ToList() ? whats the consideration of default sorting when using ToList()? – muhammad kashif Jan 16 '14 at 13:41
  • even though I changed my where clause to convert into List via ToList() but order is still changing. – muhammad kashif Jan 16 '14 at 13:43