Suppose I have var lst = List<Foobar> that I populated in loop. I cannot modify the Foobar object.
What would be the best way to effectively do an OrderBy on one property in an IEnumerable, but preserve the original order in case they are equal? For example, if I had this:
var lst = new List<Foobar> {
new Foobar{Foo = "b", Bar=3},
new Foobar{Foo = "b", Bar=1},
new Foobar{Foo = "a", Bar=2}
}
I would want to ensure I'd get back the following after lst.OrderByWithPreserveOrder(x => x.Foo).ToList:
List<Foobar> {
new Foobar{Foo = "a", Bar=2}
new Foobar{Foo = "b", Bar=3},
new Foobar{Foo = "b", Bar=1},
}
The implementation of OrderBy is already a stable sort, which is to say that it will maintain the original ordering in the event that objects are equal.
Assuming OrderBy was not a stable sort, this is one way I could think of doing it with a single LINQ statement:
list.Select((element, index) => new { Element = element,
Index = index})
.OrderBy(a => a.Element.Foo)
.ThenBy(a => a.Index)
.Select(a => a.Element);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With