OrderBy, ThenBy and IOrderedEnumerable <T>

    string[] fruits = { "grape", "passionfruit", "banana", "mango", 
                          "orange", "raspberry", "apple", "blueberry" };

    // Sort the strings first by their length and then 
    //alphabetically by passing the identity selector function.
    IEnumerable<string> query =
        fruits.OrderBy(fruit => fruit.Length).ThenBy(fruit => fruit);

If we need more ordering than is possible with a single call OrderBy, then we should then call ThenByOrderBy instead, since the sorting performed ThenByis stable and thus preserves the order of input elements with the same key values.

a) In the above example, it OrderByreturns the IOrderedEnumerable<>sequence R and, in turn, ThenByis called in this sequence. When ROrderBy returns , R also stores the key values ​​( values) that were used to sort the elements in R ?fruit.LengthOrderBy

b) Where are key R values ​​stored ?

thank

+3
source share
3 answers

I think the answer to this question lies somewhere else than you think;

OrderByand ThenBy- these are the so-called "deferred statements". What you described as behavior is correct at some level, but in reality ...

OrderByreturns a reference of the type you are suggesting. But this object is not a collection in the traditional sense; It is part of the expression tree. Subsequent calls ThenByfurther modify this expression tree.

, . , , ( , ).

, OrderBy ThenBy , ... . , OrderBy, ...

var names = //initialize list of names;
var namesByAlpha = BubbleSort(names=>names);
var namesByAlphaAndLength = BubbleSort(namesByAlpha=>namesByAlpha.Length);

, BubbleSort - , , , , , ( ), , ... , LINQ, ... , alpha first. , , OrderBy "", .

OrderBy ThenBy, , Bubble Sort ( ), , , , , , . , ... .

+5

"". OrderBy , , .

+2

. , :

// enumerate the sorted list
foreach (string fruit in query) {
    int length = fruit.Length;  // grab the key value
    // do something with key value
}

, ? , GroupBy, ?

+1

All Articles