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

}

}

Leave a Comment


x

You might be Interested in these Posts

C Program to convert lower case string to upper case

Problem Statement Write a program in C to convert the given string from lower case to upper case. ...

How to decode a base64 string in C#?

Here's a sample code snippet demonstrating how you can easily decode a base64 encoded string in C#. ...

How to disable editing of items in a combo box in c#?

When working in Win forms using C# and especially when you use the combo box , you would have notice...