CSharp examples for LINQ:Query Array
Querying an array of Employee objects
using System;/*from w ww.j av a 2 s. c o m*/ 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); } // filter a range of salaries using && in a LINQ query var between4K6K = from e in employees where (e.MonthlySalary >= 4000M) && (e.MonthlySalary <= 6000M) select e; // display employees making between 4000 and 6000 per month Console.WriteLine("\nEmployees earning in the range " + $"{4000:C}-{6000:C} per month:"); foreach (var element in between4K6K) { 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}"; }