OrderByDescending Method
Sorts the elements of a sequence in descending order according to a key.
This method supports and can be called from the LINQ to Objects and LINQ to SQL providers.
Parameters
Name | Type | Description |
---|---|---|
source | IEnumerable<TSource> | An IEnumerable<TSource> whose elements to order. |
keySelector | Func<TSource, TKey> | A function to extract a key from each element. |
Return Value
IEnumerable<TSource>: An IEnumerable<TSource> that has elements that are sorted in descending order.
Remarks
Use the OrderByDescending method to perform a descending sort on a sequence of elements. You can specify a key to sort by, and the elements will be arranged from the largest key to the smallest.
The order of elements with equal keys is preserved. For example, if two elements have the same key, their relative order in the output sequence will be the same as their relative order in the input sequence.
This method performs an inline sort, meaning it does not modify the original sequence. It returns a new sequence with the elements sorted.
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 = "Laptop", Price = 1200.00m },
new Product { Name = "Mouse", Price = 25.50m },
new Product { Name = "Keyboard", Price = 75.00m },
new Product { Name = "Monitor", Price = 300.00m },
new Product { Name = "Webcam", Price = 50.00m }
};
// Sort products by price in descending order
var sortedProducts = products.OrderByDescending(p => p.Price);
Console.WriteLine("Products sorted by price (descending):");
foreach (var product in sortedProducts)
{
Console.WriteLine($"- {product.Name}: ${product.Price}");
}
}
}