Use LINQ to select first and last names - CSharp LINQ

CSharp examples for LINQ:Select

Description

Use LINQ to select first and last names

Demo Code


using System;// w w w . j  av  a 2  s.co m
using System.Linq;

class MainClass
{
   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);
      }


      // use LINQ to select first and last names
      var names =
         from e in employees
         select new { e.FirstName, e.LastName };

      // display full names
      Console.WriteLine("\nNames only:");
      foreach (var element in names)
      {
         Console.WriteLine(element);
      }

   }
}

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