Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Maintain subsequence order in OrderBy

Suppose I have a class with an integer Day property and an IEnumerable<T> of objects where the days are 2, 3, 4, 1, 3, 3 and 5 (in that order).

Is there a way to guarantee that the order of the subsequence where (for example) o.Day == 3 is maintained from its elements' relative positions in the original list without requiring an explicit, custom implementation of IEnumerable?

like image 268
Ant P Avatar asked Nov 07 '13 11:11

Ant P


2 Answers

OrderBy is documented as being stable, if that is what you mean; so: you shouldn't need to do anything.

Enumerable.OrderBy

This method performs a stable sort; that is, if the keys of two elements are equal, the order of the elements is preserved. In contrast, an unstable sort does not preserve the order of elements that have the same key.

like image 129
Marc Gravell Avatar answered Nov 17 '22 00:11

Marc Gravell


Is there a way to guarantee that the order of the subsequence where

Assuming you have class like this:

class A
{
    public string Name { get; set; }
    public int Day { get; set; }

    // other properties
}

and the sequence:

{ "A", 2 },
{ "B", 3 },
{ "C", 4 },
{ "D", 1 },
{ "E", 3 },
{ "F", 3 },
{ "G", 5 },

If you mean, will this:

sequence.Where(item => item.Day == 3)

produce the sequence, where items will be ordered like this: B, E, F, then the answer is "no, you nave no guarantee".

If your sequence is a List<A>, than ordering will be preserved (indeed, it will be preserved with LINQ to Objects, not only with lists).

If you sequence is IQueryable<A>, then the ordering may depend from the LINQ provider implementation, underlying data source and current expression tree, already contained in IQueryable<A>. So, in this case you should force ordering with OrderBy/OrderByDescending.

like image 1
Dennis Avatar answered Nov 16 '22 23:11

Dennis