C# Program to Print Employees Whose Salary is Greater than Average of all Employees Salaries Using LINQ
Last Updated :
29 Dec, 2022
LINQ is known as Language Integrated Query and it is introduced in .NET 3.5. It gives the ability to .NET languages to generate queries to retrieve data from the data source. It removes the mismatch between programming languages and databases and the syntax used to create a query is the same no matter which type of data source is used. In this article, we will learn how to display a list of those employees’ details whose salary is greater than the average of all employee salaries.
Example:
Input:
{{emp_Name = "sravan", emp_Age = 21, emp_Salary = 26199},
{emp_Name = "ramya", emp_Age = 22, emp_Salary = 19000},
{emp_Name = "harsha", emp_Age = 23, emp_Salary = 25000},
{emp_Name = "deepu", emp_Age = 23, emp_Salary = 23456},
{emp_Name = "jyothika", emp_Age = 21, emp_Salary = 21345}}
Output:
{emp_Name = "sravan", emp_Age = 21, emp_Salary = 26199}
{emp_Name = "harsha", emp_Age = 23, emp_Salary = 25000}
{emp_Name = "deepu", emp_Age = 23, emp_Salary = 23456}
Input:
{{emp_Name = "sravan", emp_Age = 21, emp_Salary = 26199},
{emp_Name = "ramya", emp_Age = 22, emp_Salary = 19000}}
Output:
{emp_Name = "sravan", emp_Age = 21, emp_Salary = 26199}
Approach:
- Declare three variables- employee name, age, and salary
- Create a list of employees using list collection.
- Using Query compute the average salary of all the employees.
- Using where clause check each employee salary which is greater than average value.
- Select that employees.
- Display the result using ToString() method.
Example:
C#
using System;
using System.Collections.Generic;
using System.Linq;
class Employee{
string emp_Name;
int emp_Age;
int emp_Salary;
public override string ToString()
{
return " " + emp_Name + " " +
emp_Age + " " + emp_Salary;
}
static void Main( string [] args)
{
List<Employee> emp = new List<Employee>()
{
new Employee{ emp_Name = "sravan" , emp_Age = 21,
emp_Salary = 26199 },
new Employee{ emp_Name = "ramya" , emp_Age = 22,
emp_Salary = 19000 },
new Employee{ emp_Name = "harsha" , emp_Age = 23,
emp_Salary = 25000 },
new Employee{ emp_Name = "deepu" , emp_Age = 23,
emp_Salary = 23456 },
new Employee{ emp_Name = "jyothika" , emp_Age = 21,
emp_Salary = 21345 }
};
IEnumerable<Employee> result =
from e in emp
let total = emp.Sum(sal => sal.emp_Salary)
let average = total / 5
where e.emp_Salary > average
select e;
Console.WriteLine( " Employee-Name Employee-Age Employee-Salary" );
foreach (Employee x in result)
{
Console.WriteLine(x.ToString());
}
}
}
|
Output:
Employee-Name Employee-Age Employee-Salary
sravan 21 26199
harsha 23 25000
deepu 23 23456
Share your thoughts in the comments
Please Login to comment...