Reputation: 133
I am trying to display even numbers from a list of integers and sort them in ascending order. My code is:
public void EvenNumbers()
{
List<int> ofNumbers = new List<int> { 1, 3, 2, 10, 15, 6, 8 };
ofNumbers.Sort();
var result = (from m in ofNumbers
where m % 2 == 0
select m).ToList();
}
But after reading Sorting a List I am trying to sort my list with the following code:
var values = new int[] { 5,7,3 };
values = values.OrderBy(p => p).ToList();
changing my code to this is not working
public void EvenNumbers()
{
List<int> ofNumbers = new List<int> { 1, 3, 2, 10, 15, 6, 8 };
var result = ofNumbers.OrderBy(from m in ofNumbers
where m % 2 == 0
select m).ToList();
}
What am I doing wrong here?
Upvotes: 1
Views: 1055
Reputation: 8743
You are mixing query syntax with method syntax. The query syntax looks really close to normal SQL:
var result = (from m in ofNumbers
where m % 2 == 0
orderby m
select m).ToList();
The method syntax expects lambda expressions:
var result = ofNumbers.Where(m => m % 2 == 0).OrderBy(m => m).ToList();
Both are compiled to the very same IL, hence you can just take the version you like most. I think the query syntax is preferred by beginners, whereas the method syntax is preferred by advanced C# coders (because it is more powerful).
Upvotes: 2
Reputation: 1848
The cause of the problem is that you are trying to combine two syntaxes:
It would be better to use just one approach. Here are examples:
Extension methods:
var result = ofNumbers.Where(m => m % 2 == 0).OrderBy(m => m).ToList();
Query:
var result = (from m in ofNumbers
where m % 2 == 0
orderby m
select m).ToList();
Upvotes: 2