Microsoft provides LINQ operators under the System.linq namespace. If fairly reduces the effort to manipulate collections. Let’s discuss below LINQ operators for changing the order of the list items. We will discuss about various scenarios of orderBy operator using query syntax and method syntax.
We are considering that we have a list of product class containing product price, category, etc. as below
public class Product
{
public int productId { get; set; }
public string productName { get; set; }
public decimal productPrice { get; set; }
public string category { get; set; }
}
OrderBy – Using Query Syntax (By Default Ascending)
var sortedProducts = from product in products
orderby product.productPrice select product;
LINQ has also provided method syntax for the same operation as below.
OrderBy – Using Method Syntax (By Default Descending)
var sortedProducts = products.OrderBy(x => x.productPrice).ToList();
Reverse sorting can be implemented by reversing the same list using the Reverse method or using below Operator.
OrderByDescending – Using Query Syntax
var sortedProducts = from product in products
orderby product.productPrice descending select product;
OrderByDescending – Using Method Syntax
var sortedProducts = products.OrderByDescending(x => x.productPrice).ToList();
Order by multiple fields/properties
List item can be sorted using multiple columns, i.e. if one field is same then second field will be used to sort it out.
Order by multiple columns – Query Syntax
var sortedProducts = from product in products
orderby product.productPrice descending , product.category
select product;
Order by multiple columns – Method Syntax
var sortedProducts = products.OrderBy(x => x.productPrice
).ThenBy(x => x.category).ToList();
Conclusion:
LINQ has 2 variants – query syntax and method syntax. In method syntax, we can pass a lambda function (x=>x.something) to provide login for sorting. We hope you find it useful.
Please let us know in the comment box below in case of any queries/suggestions.