There are scenarios where one might want to implement multiple order by statements when using LINQ in C#.
For example, you might want to sort the list of article by category and then by date. Below is a sample code snippet that demonstrates how to How to Implement Multiple order by in LINQ using C# ?
How to Implement Multiple order by in LINQ using C#?
using System; using System.Collections.Generic; using System.Data; using System.Linq; namespace AbundantCode { internal class Program { //How to Implement Multiple order by in LINQ using C# ? private static void Main(string[] args) { List<Article> Articles = new List<Article>(); Articles.Add(new Article { Title = "LINQ Program1 ", Category = "C#", ArticleDate = new DateTime(2013, 5, 1) }); Articles.Add(new Article { Title = "LINQ Program2 ", Category = "VB.NET", ArticleDate = new DateTime(2013, 1, 1) }); Articles.Add(new Article { Title = "LINQ Program4 ", Category = "Java", ArticleDate = new DateTime(2013, 2, 1) }); Articles.Add(new Article { Title = "LINQ Program3 ", Category = "C#", ArticleDate = new DateTime(2013, 1, 3) }); var articlelst = Articles.OrderBy(c => c.Category).ThenBy(n => n.ArticleDate); foreach (var item in articlelst) { Console.WriteLine(item.Title); } Console.ReadLine(); } } public class Article { public string Title { get; set; } public string Category { get; set; } public DateTime ArticleDate { get; set; } } }
Leave a Reply