OrderBy Method
public static
IEnumerable<TSource>
OrderBy<TSource, TKey>(
this IEnumerable<TSource> source,
Func<TSource, TKey> keySelector
)
Sorts the elements of a sequence in ascending order by using a specified key selector function.
Parameters
-
source
An
IEnumerable<TSource>
whose elements to order. -
keySelector
A function to extract a key from each element.
Returns
An IEnumerable<TSource>
that has elements from the input sequence sorted in ascending order.
Exceptions
-
ArgumentNullException
source
orkeySelector
is null.
Remarks
The OrderBy
method performs a stable sort; that is, the relative order of elements that have equal keys is preserved.
This method uses deferred execution. The values of source
and keySelector
are not immediately sent to the query.
For more information on how deferred execution is implemented, see Deferred Execution.
Example
using System;
using System.Collections.Generic;
using System.Linq;
public class Product
{
public string Name { get; set; }
public decimal Price { get; set; }
}
public class Example
{
public static void Main(string[] args)
{
List<Product> products = new List<Product>()
{
new Product() { Name = "Apple", Price = 1.20m },
new Product() { Name = "Banana", Price = 0.50m },
new Product() { Name = "Orange", Price = 0.75m },
new Product() { Name = "Grape", Price = 2.50m },
new Product() { Name = "Strawberry", Price = 3.00m }
};
// Order products by price in ascending order
var orderedProducts = products.OrderBy(p => p.Price);
Console.WriteLine("Products ordered by price:");
foreach (var product in orderedProducts)
{
Console.WriteLine($"- {product.Name}: {product.Price:C}");
}
}
}