📜  使用 LINQ 实现 IEnumerable 接口的 C# 程序

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

使用 LINQ 实现 IEnumerable 接口的 C# 程序

LINQ 被称为语言集成查询,它是在 .NET 3.5 中引入的。它使 .NET 语言能够生成查询以从数据源中检索数据。它消除了编程语言和数据库之间的不匹配,并且无论使用哪种类型的数据源,用于创建查询的语法都是相同的。在本文中,我们将使用 LINQ 实现一个 IEnumerable 接口。此接口用于迭代列表、堆栈、队列等集合。或者我们可以说此接口是所有可以枚举的非泛型集合的基本接口。

句法:

IEnumerable

使用 IEnumerable,我们将显示名称以“D”开头的员工数据。

示例

Input : List of Employees:
        {{id = 201, name = "Druva", age = 12},
         {id = 202, name = "Deepu", age = 15},
         {id = 203, name = "Manoja", age = 13},
         {id = 204, name = "Sathwik", age = 12},
         {id = 205, name = "Suraj", age = 15}}
Output : {{id = 201, name = "Druva", age = 12},
          {id = 202, name = "Deepu", age = 15}}
 
Input : List of Employees:
        {{id = 301, name = "Sathwik", age = 12},
         {id = 302, name = "Saran", age = 15}}
Output : No Output

方法

例子:

C#
// C# program to display the details of those 
// employees whose name starts with character "D"
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
  
class Employee{
      
// Declare 4 variables - id, name, 
// department, and salary
int id; 
int salary;
string name;
string department;
  
// Get the to string method that returns 
// id, name, department, and salary
public override string ToString()
{
    return id + " " + name + " " + 
       salary + " " + department;
}
  
// Driver code
static void Main(string[] args)
{
      
    // Declare a list variable 
    List emp = new List()
    {
          
        // Create 5 Employee details
        new Employee{ id = 201, name = "Druva", 
                      salary = 12000, department = "HR" },
        new Employee{ id = 202, name = "Deepu", 
                      salary = 15000, department = "Development" },
        new Employee{ id = 203, name = "Manoja", 
                      salary = 13000, department = "HR" },
        new Employee{ id = 204, name = "Sathwik", 
                      salary = 12000, department = "Designing" },
        new Employee{ id = 205, name = "Suraj", 
                      salary = 15000, department = "Development" }
    };
      
    // Iterate the Employee by selecting Employee 
    // name starts with D
    // Using IEnumerable interface
    IEnumerable result = emp.Where(x => x.name[0] == 'D');
      
    // Display employee details
    Console.WriteLine("ID  Name  Salary  Department");
    Console.WriteLine("++++++++++++++++++++++++++++");
    foreach (Employee e in result)
    {
          
        // Call the to string method
        Console.WriteLine(e.ToString());
    }    
}
}


输出:

ID  Name  Salary  Department
++++++++++++++++++++++++++++
201 Druva 12000 HR
202 Deepu 15000 Development