Reputation: 1231
I have a List of numbers that I want to order.
List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
It works fine if I do
.OrderBy(n => n)
Just for the heck of it, I tried
.OrderBy(n => "ASC")
It didn't work, but it was not throwing an error. And If I hover over OrderBy, the intellisense shows,
IOrderedEnumerable<int> IEnumerable<int>.OrderBy<int,string>(Func<int,string> keySelector)
Just curious, why is that?
Thanks.
Upvotes: 1
Views: 201
Reputation: 1128
It works, but it doesn't work as you want, cause you compare using "ASC".
If you want to order numbers use:
.OrderBy(i => i);
.OrderByDescending(i => i);
Upvotes: 0
Reputation: 13158
You are saying to sort the objects by some value, where each value to sort by is obtained through each object; normally this would be a property or function of that object. You can think of it like a 'column' in a database or spreadsheet.
Ex:
var employeesByName = Employees.OrderBy(employee => employee.Name);
gives an enumerable of employee objects ordered by their name values. If you were instead to do this:
var employeesByConstant = Employees.OrderBy(employee => "ASC");
then you are getting an enumerable of employee objects that are ordered by a 'column' in which all of the values are "ASC". Depending on the sort algorithm used this may have no effect, or some arbitrary ordering.
Upvotes: 0
Reputation: 2451
As others note, this is because this is perfectly legal. You could also do something like this:
Enumerable.Range(0,20).OrderBy(x=>x.ToString());
You'll get the integers ordered... alphabetically.
0
1
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
Upvotes: 0
Reputation: 8131
This method compare keys using default comparer. The key for each element is "ASC". Not illegal.
Upvotes: 1
Reputation: 12630
It wouldn't throw an error. You are telling it to compare using "ASC"
, and it is doing just that.
Upvotes: 4