Inconsistent linq query return types with orderby clauses

Does anyone know why the result types of these two queries are different?

// q1 is IOrderedEnumerable<int>
var q1 = from c1 in new[] { 1, 2, 3 }
         orderby c1
         select c1;

// q2 is IEnumerable<int>
var q2 = from c1 in new[] { 1, 2, 3 }
         from c2 in new[] { 1, 2, 3 }
         where c1 == c2
         orderby c1
         select c1;

I can not understand why q2 is also not IOrderedEnumerable<int>.

Using the join clause doesn't matter:

// q3 is IEnumerable<int>
var q3 = from c1 in new[] { 1, 2, 3 }
         join c2 in new[] { 1, 2, 3 }
         on c1 equals c2
         orderby c1
         select c1;
+4
source share
2 answers

In the very first request, the actual work is not performed Select. Selectselects the current item in a sequence that is not an operator, so the call is Selectsimply skipped. If there is no call, it Select OrderByis the last call in the request and returns IOrderedEnumerable<T>.

( ) Select - . ( SelectMany IEnumerable , Join .) , Select Select IEnumerable<T>.

, , , :

var q1a = new[] { 1, 2, 3 }.OrderBy(c1 => c1);

var q2a = new[] { 1, 2, 3 }.SelectMany(c1 => new[] { 1, 2, 3 }.Select(c2 => new { c1, c2 }))
    .Where(variables => variables.c1 == variables.c2)
    .OrderBy(variables => variables.c1)
    .Select(variables => variables.c1);

var q3a = new[] { 1, 2, 3 }.Join(new[] { 1, 2, 3 }, c1 => c1, c2 => c2, (c1, c2) => new { c1, c2 })
    .OrderBy(variables => variables.c1)
    .Select(variables => variables.c1);

, , , IOrderedEnumerable<int>.

+5

(, ):

q1: OrderedEnumerable<int, int>

q2: Enumerable+WhereSelectEnumerableIterator<AnonymousType<int, int>, int>

(q3 , q2)

-3

Source: https://habr.com/ru/post/1677874/