Suppose we have a class Foo
which has an Int32
Field Bar
and you want to sort the collection of the Foo
objects by the Bar
Value. One way is to implement IComparable
's CompareTo()
method, but it can also be done using Language Integrated Query (LINQ) like this
List<Foo> foos = new List<Foo>();
// assign some values here
var sortedFoos = foos.OrderBy(f => f.Bar);
now in sortedFoos
we have foos
collection which is sorted. But if you use System.Diagnostics.StopWatch
object to measure the time it took OrderBy()
to sort the collection is always 0 milliseconds. But whenever you print sortedFoos
collection it's obviously sorted. How is that possible. It takes literary no time to sort collection but after method execution the collection is sorted ? Can somebody explain to me how that works ? And also one thing. Suppose after sorting foos
collection I added another element to it. now whenever I print out the collection the the element I added should be in the end right ? WRONG ! The foos
collection will be sorted like, the element I added was the part of foos
collection even if I add that element to foos
after sorting. I don't quit understand how any of that work so can anybody make it clear for me ?!