Pouyan Saraf

0 %
Pouyan Saraf
Front-end Deweloper
Ui/UX Designer
  • Residence:
    United Kingdom
  • City:
    Stockport
  • Age:
    42
English
French
German
C#
LINQ
SQL
PHP
Python
  • Bootstrap, Materialize
  • Stylus, Sass, Less
  • Gulp, Webpack, Grunt
  • GIT knowledge

Sorting Records in a List

7 September 2021

if you want to sort list of record objects

using System;
using System.Collections.Generic;
using System.Linq;
class Program
    {
        public record Person(int Id, string FirstName, string LastName);
        static void Main(string[] args)
        {
            List<Person> people = new List<Person>();
            people.Add(new Person(2, "Sajad", "Saraf"));
            people.Add(new Person(2, "Pouyan", "Saraf"));
            people.Add(new Person(1, "Shadi", "Khanzadeh"));
            people.Add(new Person(4, "Deanerys", "Saraf"));
            people.Add(new Person(3, "Edwin", "Saraf"));
            //1: Sort people list
            people.Sort((x, y) => x.Id.CompareTo(y.Id));
            //2: Or creat new sorted list from people
            List<Person> sortedPeople = people.OrderBy(x => x.Id).ToList();
            //3: First Sort Id then FirstName
            List<Person> sortedPeopleList = people.OrderBy(x => x.Id).ThenBy(x => x.FirstName).ToList();
            Console.WriteLine("The first method of sorting:");
            foreach (var item in people)
            {
                Console.WriteLine($"{item.Id}: {item.FirstName} {item.LastName}");
            }
            Console.WriteLine("**********");
            Console.WriteLine("The second method of sorting:");
            foreach (var item in sortedPeople)
            {
                Console.WriteLine($"{item.Id}: {item.FirstName} {item.LastName}");
            }
            Console.WriteLine("**********");
            Console.WriteLine("The third method of sorting:");
            foreach (var item in sortedPeopleList)
            {
                Console.WriteLine($"{item.Id}: {item.FirstName} {item.LastName}");
            }
        }
    }
Posted in C# Sample CodeTags:
Write a comment