using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main()
{
// A list of employees, which would come from a database
var emps = new List<Employee>
{
new Employee { Name = "Ann", Age = 31, Gender = "F", Salary = 50000 },
new Employee { Name = "Brian", Age = 25, Gender = "M", Salary = 40000 },
new Employee { Name = "Cara", Age = 50, Gender = "F", Salary = 65000 },
new Employee { Name = "Dave", Age = 33, Gender = "M", Salary = 52000 }
};
// Loop through them all to find the highest salary
var highestSalary = 0m;
var highestSalaryName = "";
foreach (var emp in emps)
{
if (emp.Salary > highestSalary)
{
highestSalary = emp.Salary;
highestSalaryName = emp.Name;
}
}
Console.WriteLine($"{highestSalaryName} earns the highest salary of ${highestSalary}.\r\n");
// output: Cara earns the highest salary of $65000.
// Same thing, but a single line of LINQ
var winner = emps.OrderByDescending(emp => emp.Salary).First();
Console.WriteLine($"{winner.Name} earns the highest salary of ${winner.Salary}.\r\n");
// output: Cara earns the highest salary of $65000.
// If we don't care about who, our LINQ gets even shorter
Console.WriteLine($"The highest salary is ${emps.Max(emp => emp.Salary)}.\r\n");
// output: The highest salary is $65000.
}
}
public class Employee
{
public string Name { get; set; }
public int Age { get; set; }
public decimal Salary { get; set; }
public string Gender { get; set; }
}