Order the employees by last name, then first name - CSharp LINQ

CSharp examples for LINQ:order by

Description

Order the employees by last name, then first name

Demo Code



using System;/*from ww  w . j  av a2  s.c om*/
using System.Linq;

class LINQWithArrayOfObjects
{
   static void Main()
   {
      // initialize array of employees
      var employees = new[] {
         new Employee("A", "X", 5432M),
         new Employee("B", "Y", 7600M),
         new Employee("C", "Z", 2657.23M),
         new Employee("D", "Z", 4700.77M),
         new Employee("E", "Z", 6527.23M),
         new Employee("A", "V", 3200M),
         new Employee("F", "W", 6257.23M)};

      // display all employees
      Console.WriteLine("Original array:");
      foreach (var element in employees)
      {
         Console.WriteLine(element);
      }

      // order the employees by last name, then first name with LINQ
      var nameSorted =
         from e in employees
         orderby e.LastName, e.FirstName
         select e;

      // header
      Console.WriteLine("\nFirst employee when sorted by name:");

      // attempt to display the first result of the above LINQ query
      if (nameSorted.Any())
      {
         Console.WriteLine(nameSorted.First());
      }
      else
      {
         Console.WriteLine("not found");
      }
   }
}

class Employee
{
   public string FirstName { get; } // read-only auto-implemented property
   public string LastName { get; } // read-only auto-implemented property
   private decimal monthlySalary; // monthly salary of employee

   public Employee(string firstName, string lastName,decimal monthlySalary)
   {
      FirstName = firstName;
      LastName = lastName;
      MonthlySalary = monthlySalary;
   }

   // property that gets and sets the employee's monthly salary
   public decimal MonthlySalary
   {
      get
      {
         return monthlySalary;
      }
      set
      {
         if (value >= 0M) // validate that salary is nonnegative
         {
            monthlySalary = value;
         }
      }
   }

   // return a string containing the employee's information
   public override string ToString() => $"{FirstName,-10} {LastName,-10} {MonthlySalary,10:C}";
}

Result


Related Tutorials