Does the upstream keyword only for clarity when used with orderby?

If I execute the query by arranging the elements as shown below, I get an ascending order.

var i = from a in new int[] { 1, 2, 3, 4, 5 } orderby a select a; 

If I add the ascending keyword, I get the same results.

 var i = from a in new int[] { 1, 2, 3, 4, 5 } orderby a ascending select a; 

I understand that adding the ascending keyword in the second example can improve readability, since it eliminates the need to know the default orderby .

Is there any other reason for the ascending keyword?

I am also interested in knowing why this (violation)? was implemented for use in one specific case only.

Edit: See the comments below, @Joey indicates that this is not an intermittent change, as it is a contextual keyword.

+8
c # keyword linq sql-order-by
source share
1 answer

Yes, this is redundant. There are no circumstances when he does something else, since the order is implicitly increasing.

I suppose it provides completeness, but it really seems embarrassing to introduce a keyword into a language that is so ... impotent.

On the other hand:

  • it mimics SQL, which is widely associated with semantics
  • he avoids "how am I?" the questions
  • It does no harm, and no one forces you to use it
  • it (perhaps) makes things clearer if you have a descending, b ascending, c descending, d ascending , etc.

An example (see comments) that order by a, order by b is actually very different from order by a, b :

 public static void Main() { var data = new[] { new { X = 1, Y = 1 }, new { X = 1, Y = 2 }, new { X = 2, Y = 1 }, new { X = 2, Y = 2 } }; foreach (var pair in from p in data orderby pX, pY select p) { Console.WriteLine("{0},{1}", pair.X, pair.Y); } Console.WriteLine(); foreach (var pair in from p in data orderby pX orderby pY select p) { Console.WriteLine("{0},{1}", pair.X, pair.Y); } } 

prints:

 1,1 1,2 2,1 2,2 1,1 2,1 1,2 2,2 

Note that the middle two are reversed. This is due to the difference between:

 data.OrderBy(p => pX).ThenBy(p => pY) 

in the first cycle and

 data.OrderBy(p => pX).OrderBy(p => pY) 

in the second.

Since LINQ tries to guarantee a stable look (i.e. when there are matches, the data is stored in the original order), OrderBy().OrderBy() performs the first sort (by X), and then resorts the data, only looking at the original (sorted by X ) the order when Ys matches. Or, in other words: he flips them left and right.

+7
source share

All Articles