Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq order by property, then by original order

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},
}
like image 428
Arithmomaniac Avatar asked Sep 17 '14 18:09

Arithmomaniac


2 Answers

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.

like image 61
Servy Avatar answered Nov 16 '22 08:11

Servy


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);
like image 36
test Avatar answered Nov 16 '22 07:11

test