📌  相关文章
📜  C# 程序使用 LINQ 的 where() 方法查找姓名以“S”开头的学生列表

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

C# 程序使用 LINQ 的 where() 方法查找姓名以“S”开头的学生列表

LINQ 被称为语言集成查询,它是在 .NET 3.5 中引入的。它使.NET语言能够生成查询以从数据源中检索数据。它消除了编程语言和数据库之间的不匹配,并且无论使用哪种类型的数据源,用于创建查询的语法都是相同的。在本文中,我们将学习如何使用 List Collection 的 where() 方法打印姓名以“S”开头的学生列表。这里的 where 方法根据谓词过滤给定的值序列或数组。要使用 where() 方法,您需要在程序中导入System.LinqSystem.Collections.Generic命名空间。

句法:

例子:

Input : List of Students:
        {{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 = 104, name = "Sathwik",age = 12},
         {id = 105, name = "Saran",  age = 15}}
     
Input: List of Students:
       {{id = 102, name = "deepu",  age = 15},
        {id = 103, name = "manoja", age = 13}}
Output: No Output

方法:

例子:

C#
// C# program to display the list of students whose 
// name starts with 'S'. Using Where() function 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
  
class Student{
      
// Declare 3 variables - id, age and name
int id; 
int age;
string name;
  
// Get the to string method that returns 
// id , name and age
public override string ToString()
{
    return id + " " + name + " " + age;
}
  
// Driver code
static void Main(string[] args)
{
      
    // Declare a list variable 
    List student = new List()
    {
          
        // Create 5 Student details
        new Student{ id = 101, name = "Sravan", age = 12  },
        new Student{ id = 102, name = "deepu", age = 15 },
        new Student{ id = 103, name = "manoja", age = 13 },
        new Student{ id = 104, name = "Sathwik", age = 12 },
        new Student{ id = 105, name = "Saran", age = 15 }
      
    };
      
    // Iterate the Student by selecting Student 
    // name starts with S
    // Using Where() function
    IEnumerable Query = student.Where(s => s.name[0] == 'S');
      
    // Display employee details
    Console.WriteLine("ID  Name  Age");
    Console.WriteLine("+++++++++++++");
    foreach (Student e in Query)
    {
          
        // Call the to string method
        Console.WriteLine(e.ToString());
    }    
}
}


输出:

ID  Name  Age
+++++++++++++
101 Sravan 12
104 Sathwik 12
105 Saran 15