Last active
April 24, 2022 11:24
-
-
Save meSailesh/626ea06dbc827e94ac8a847084ff3a03 to your computer and use it in GitHub Desktop.
Sort list based on other sorted list using LINQ in c sharp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using Newtonsoft.Json; | |
public class SortList | |
{ | |
public static void Main(string[] args) | |
{ | |
List<Student> students = new List<Student>(){ | |
new Student {name ="Bob", standard = "Third", section ="A", rollNumber=10}, | |
new Student {name ="Smith", standard = "Second", section ="B", rollNumber=5}, | |
new Student {name ="Tylor", standard = "first", section ="A", rollNumber=1}, | |
new Student {name ="Jack", standard = "Third", section ="A", rollNumber=8}, | |
new Student {name ="Penny", standard = "second", section ="B", rollNumber=4}, | |
new Student {name ="Diana", standard = "First", section ="A", rollNumber=1}, | |
new Student {name ="Selena", standard = "First", section ="B", rollNumber=3}, | |
new Student {name ="Elon", standard = "Second", section ="A", rollNumber=1}, | |
new Student {name ="Harry", standard = "Second", section ="B", rollNumber=1}, | |
}; | |
List<string> sortedStandard = new List<string>() {"Second", "First", "Third"}; | |
List<string> sortedSection = new List<string>() {"B", "A"}; | |
List<Student> sortedStudents = students. | |
OrderBy(x => sortedStandard.IndexOf(x.standard)). | |
ThenBy(x => sortedSection.IndexOf(x.section)). | |
ThenBy(x => x.rollNumber).ToList(); | |
foreach(Student student in sortedStudents) { | |
Console.WriteLine(JsonConvert.SerializeObject(student)); | |
} | |
} | |
} | |
public class Student{ | |
public string name {get; set;} | |
public string standard { get; set;} | |
public string section {get; set;} | |
public int rollNumber {get; set;} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment