If you are working with C# List, then there is a possibility, you may want to sort C# list using Multiple database table columns or multiple fields or multiple properties using OrderBy Method in Linq, so in this article, I have mentioned a working console application example for that.
The simple method to sort a C# list using multiple fields is to use List.OrderBy(a=>a.Field1).ThenBy(a => a.Field2)
, let's take a look at an example of using this code.
using System;
using System.Collections.Generic;
using System.Linq;
namespace SortingList
{
internal class Program
{
static void Main(string[] args)
{
List<Students> students = new List<Students>();
students.Add(new Students { FirstName ="Hitesh", LastName="Manwani" });
students.Add(new Students { FirstName = "Hitesh", LastName = "Vaswani" });
students.Add(new Students { FirstName = "Vikram", LastName = "Vaswani" });
students.Add(new Students { FirstName = "Vikram", LastName = "Devnani" });
students.Add(new Students { FirstName = "Joel", LastName = "James" });
//we are sorting list by Firstname and then by LastName
var sortedList = students.OrderBy(s => s.FirstName).ThenBy( s => s.LastName).ToList();
Console.WriteLine("List of Student after Sorting");
foreach (var stu in sortedList)
{
Console.WriteLine(stu.FirstName + " "+ stu.LastName);
}
}
public class Students
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
}
}
As you can see from above code, we are sorting Students List by FirstName intially and then LastName.
So output would be
List of Student after Sorting
Hitesh Manwani
Hitesh Vaswani
Joel James
Vikram Devnani
Vikram Vaswani
If you have more than 2 fields to sort list in C#, then you can use .ThenBy Again, suppose you want to Sort a list using 3 database table Columns, then it would have code as below
var sortedList = youList.OrderBy(s => s.ColumnOne).ThenBy( s => s.ColumnTwo).ThenBy( s => s.ColumnThree).ToList();
That's it.
You may also like to read:
Sort Dictionary by Value in C#
Visual Studio Code Intellisense (autocomplete) not working
Open and Read XML in C# (Examples using Linq, XMLReader, XMLDocument)
How can I convert string to time in C#?
Resize image in C# (Console application example)
Using Generics in C# (With Example)
Extract Text from image in C# using Tesseract
How to convert seconds into hh:mm:ss in C#?
Verify email address exists or not? (With email id validation in C#)