LINQ in C# - Examples - OrderBy, OrderByDescending, ThenBy, ThenByDescending- Ordering

  • The ordering operators allow input sequences to be ordered.
  • It is important to notice that both the OrderBy and OrderByDescending operators require an input sequence of type IEnumerable<T> and return a sequence of type IOrderedEnumerable<T>.
  • In simple terms, If you need more ordering than is possible with a single call to the OrderBy or OrderByDescending operators, you should subsequently call the ThenBy or ThenByDescending operators.
  • You may chain calls to the ThenBy and ThenByDescending operators to subsequent calls to the ThenBy and ThenByDescending operators, because they accept an IOrderedEnumerable<T> as their input sequence and return an IOrderedEnumerable<T> as their output sequence.
  •   Type 1 - Example -1

class Student
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
    class Course
    {
        public int courseId;
        public string courseName;
        public List<Student> students;


        public static List<Course> GetCourses()
        {
            List<Course> courses = new List<Course> {
        new Course {
            courseId = 1,
            courseName = "Course 1",
            students =  new List<Student> { new Student { FirstName = "Ravi", LastName = "Kumar" },
                                            new Student { FirstName = "Raj", LastName = "Kumar" },
                                            new Student { FirstName = "Mani", LastName = "Kannan" },}
        },
        new Course {
            courseId = 2,
            courseName = "Course 2",
            students = new List<Student> { new Student { FirstName = "John", LastName = "Peterson" },
                                            new Student { FirstName = "Michel", LastName = "Jakson" },
                                            new Student { FirstName = "Steve", LastName = "Adam" },}
        },
        new Course {
            courseId = 3,
            courseName = "Course 3",
            students = new List<Student> { new Student { FirstName = "Mani", LastName = "Raj" },
                                            new Student { FirstName = "Raguram", LastName = "Rajan" },
                                            new Student { FirstName = "Ram", LastName = "Nishanth" },}
        }
    };
            return courses;
        }
    }

    class Program
    {      
        static void Main(string[] args)
        {

            List<Course> Courses = Course.GetCourses();

            List<Student> StudentsList = Courses.SelectMany(x => x.students).OrderBy(x => x.FirstName).ThenBy(x => x.LastName).ToList();

            foreach  (var item in StudentsList)
            {
                Console.WriteLine($"{item.FirstName} {item.LastName}");
            }
            Console.ReadLine();
        }
    }

//Output
John Peterson
Mani Kannan
Mani Raj

Michel Jakson
Raguram Rajan
Raj Kumar
Ram Nishanth
Ravi Kumar
Steve Adam
  • Type 1 - Example -2

  • Change ordering and see results
List<Student> StudentsList = Courses.SelectMany(x => x.students).OrderBy(x => x.FirstName).ThenByDescending(x => x.LastName).ToList();

//Output
John Peterson
Mani Raj
Mani Kannan

Michel Jakson
Raguram Rajan
Raj Kumar
Ram Nishanth
Ravi Kumar
Steve Adam
  • Type 2 - Sorting Custom Types with IComparable<T> - Example

  • While Sorting Custom Types it is mandatory to implement IComparable interface on the target type
class Point:IComparable<Point>
    {
        public int x { get; set; }
        public int y { get; set; }

        public int CompareTo(Point other)
        {
           return this.x.CompareTo(other.x);
        }
    }
    class Program
    {      
        static void Main(string[] args)
        {

            List<Point> Points = new List<Point> {
                                    new Point(){ x=10, y=20 },
                                    new Point(){ x=-1, y=23 },
                                    new Point(){ x=-4, y=-9 },
                                    new Point(){ x=50, y=67 },
                                  
                                 };

            Points = Points.OrderBy(x => x).ToList();


            foreach  (var item in Points)
            {
                Console.WriteLine($"{item.x} {item.y}");
            }
            Console.ReadLine();
        }
    }

//Output
-4 -9
-1 23
10 20
50 67
  • Type 3 - Sorting Custom Types with Custom IComparer class- Example

  • While Sorting Custom Types using Custom IComparer class it not is mandatory to implement IComparable interface on the target type
class PointComparer : IComparer<Point>
    {
        public int Compare(Point p1, Point p2)
        {
            return p1.x.CompareTo(p2.x);
        }
    }

    class Point
    {
        public int x { get; set; }
        public int y { get; set; }       
    }
    class Program
    {      
        static void Main(string[] args)
        {

            List<Point> Points = new List<Point> {
                                    new Point(){ x=10, y=20 },
                                    new Point(){ x=-1, y=23 },
                                    new Point(){ x=-4, y=-9 },
                                    new Point(){ x=50, y=67 },
                                  
                                 };

            Points = Points.OrderBy((x => x), new PointComparer()).ToList();


            foreach  (var item in Points)
            {
                Console.WriteLine($"{item.x} {item.y}");
            }
            Console.ReadLine();
        }
    }

//Output
-4 -9
-1 23
10 20
50 67

No comments:

Post a Comment

Framework Fundamentals - String - Comparing Strings

In comparing two values, the .NET Framework differentiates the concepts of equality comparison and order comparison . Equality compariso...