CSharp examples for LINQ:Select
Select employee last names
using System;// w w w . ja va2 s . c o 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 employee last names var lastNames = from e in employees select e.LastName; // use method Distinct to select unique last names Console.WriteLine("\nUnique employee last names:"); foreach (var element in lastNames.Distinct()) { 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}"; }