How to Implement Multiple order by in LINQ using C#?

Published on June 9, 2013 by abundantcode

Filed under LINQ

Last modified June 9, 2013

Print this page

rate 1 star rate 2 star rate 3 star rate 4 star rate 5 star
Your rating: none, Average: 0 (0 votes)

This article have been viewed 4092 times

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; }

}

}

0saves
If you enjoyed this post, please consider leaving a comment or subscribing to the RSS feed to have future articles delivered to your feed reader.

Leave a Comment


x

You might be Interested in these Posts

VB.NET and LINQ – Filter elements from object collection with Logical Operators

Here’s a sample code snippet demonstrating how to filter elements from a list of objects using the w...

C# and LINQ – Filter elements from object collection with Logical Operators

Here’s a sample code snippet demonstrating how to filter elements from a list of objects using the w...

VB.NET and LINQ – Filter elements from object collection using where clause

Here’s a sample code snippet demonstrating how to filter elements from a list of objects using the w...