I have a list which is ordered using the OrderBy()
Linq function, that returns an IOrderedEnumerable
.
var testList = myList.OrderBy(obj => obj.ParamName);
The ParamName is an object that can hold integer as well as string. The above orderBy orders the list based on the integer value. Now I am operating a foreach on the testList and changing the ParamName property to some string based on its integer value as follows,
using (var sequenceEnum = testList.GetEnumerator())
{
while (sequenceEnum.MoveNext())
{
sequenceEnum.Current.ParamName = GetStringForInteger(int.Parse(Convert.ToString(sequenceEnum.Current.ParamName)));
}
}
What has happened next is that the order of the items in the list after the previous loop has been disrupted and the list has been ordered based on the string assigned and not on the initial ordering.
However the ordering is preserved, when I am using .ToList()
in conjunction with the .OrderBy()
clause.
Can anyone please help me what is happening here?
Sample Output Illustration:
Edit: We all got your problem wrong. The reason it is sorting the wrong way is because you are comparing "B" and "AA" and expecting AA to be after B like in excel which of course will not happen in an alphabetical order.
Specify an explicit comparator while ordering or transform the ParamName into Int before doing the order by.
The reason why Linq is usually returning IEnumerable elements is that it has a lazy evaluation behaviour. This means that it will evaluate the result when you need it, not when you build it.
Calling the ToList forces linq to evaluate the result in order to generate the expected list.
TL;DR be very carefull when doing linq queries and altering the source data set before fetching the result.