C# Program to Print the Employees Whose Last Character of Name is ‘n’ Using LINQ
Last Updated :
16 Oct, 2021
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 study how to print the list of employee’s names whose last character of the name is ‘n’ using LINQ.
Example:
Input : List of Employees:
{{id = 101, name = "Sravan", age = 12},
{id = 102, name = "deepu", age = 15},
{id = 103, name = "manoja", age = 13},
{id = 104, name = "Sathwik", age = 12},
{id = 105, name = "Saran", age = 15}}
Output: {{id = 105, name = "sravan", age = 15},
{id = 105, name = "Saran", age = 15}}
Input: List of Employees:
{{id = 102, name = "deepu", age = 15},
{id = 103, name = "manoja", age = 13}}
Output: No Output
Approach:
To find the list of employees whose name ends with ‘n’ character follow the following steps:
- Create a list of employees with four variables(Id, name, department, and team).
- Iterate through the employee details and get the employee details by choosing employee name ends with ‘n’ using the following queries:
IEnumerable<Employee> Query = from emp in employees
where emp.name[emp.name.Length - 1] == 'n'
select emp;
- Now call the ToString() method.
- Display the employee details.
Example:
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
class Employee{
int id;
string name;
string department;
public override string ToString()
{
return id + " " + name + " " + department;
}
static void Main( string [] args)
{
List<Employee> emp = new List<Employee>()
{
new Employee{ id = 101, name = "Sravan" ,
department = "Development" },
new Employee{ id = 102, name = "deepu" ,
department = "HR" },
new Employee{ id = 103, name = "manoja" ,
department = "Development" },
new Employee{ id = 104, name = "Sathwik" ,
department = "Development" },
new Employee{ id = 105, name = "Saran" ,
department = "HR" }
};
IEnumerable<Employee> result = from e in emp
where e.name[e.name.Length - 1] == 'n'
select e;
Console.WriteLine( "ID Name Department" );
Console.WriteLine( "++++++++++++++++++++" );
foreach (Employee x in result)
{
Console.WriteLine(x.ToString());
}
}
}
|
Output:
ID Name Department
++++++++++++++++++++
101 Sravan Development
105 Saran HR
Share your thoughts in the comments
Please Login to comment...