📌  相关文章
📜  使用 LINQ 打印姓名最后一个字符为“n”的员工的 C# 程序

📅  最后修改于: 2022-05-13 01:55:47.547000             🧑  作者: Mango

使用 LINQ 打印姓名最后一个字符为“n”的员工的 C# 程序

LINQ 被称为语言集成查询,它是在 .NET 3.5 中引入的。它使 .NET 语言能够生成查询以从数据源检索数据。它消除了编程语言和数据库之间的不匹配,并且无论使用哪种类型的数据源,用于创建查询的语法都是相同的。在本文中,我们将研究如何使用 LINQ 打印姓名最后一个字符为“n”的员工姓名列表。

例子:

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

方法:

例子:

C#
IEnumerable Query = from emp in employees
                              where emp.name[emp.name.Length - 1] == 'n'
                              select emp;


输出:

// C# program to display the list of employees
// whose last character of the name is 'n' 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
  
// Create a class with four variables
// employee id, name, and department
class Employee{
      
int id;
string name;
string department;
  
// To string method
public override string ToString()
{
    return id + " " + name + " " + department;
}
  
// Driver code
static void Main(string[] args)
{
      
    // Create list of employees with 5 data
    List emp = new List()
    {
        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" }
    };
      
    // Condition to get employee name ends with 'n'
    IEnumerable result = from e in emp
                                   where e.name[e.name.Length - 1] == 'n'
                                   select e;
  
    Console.WriteLine("ID  Name  Department");
    Console.WriteLine("++++++++++++++++++++");
      
    // Iterating the employee data to display 
    // By calling the to string method
    foreach (Employee x in result)
    {
        Console.WriteLine(x.ToString());
    }
}
}