使用 Select Clause LINQ 显示学生详细信息的 C# 程序
LINQ 被称为语言集成查询,它是在 .NET 3.5 中引入的。它使 .NET 语言能够生成查询以从数据源中检索数据。它消除了编程语言和数据库之间的不匹配,并且无论使用哪种类型的数据源,用于创建查询的语法都是相同的。在本文中,我们将学习如何使用 LINQ 中的 select 子句打印学生列表及其详细信息。当我们想从给定的集合中选择一些特定的值时,使用 Select 子句。
句法:
IEnumerable
例子:
Input :
{ stu_id = 101, stu_name = "bobby",
stu_dept = "cse", stu_salary = 8900 },
{ stu_id = 102, stu_name = "sravan",
stu_dept = "ece", stu_salary = 8900 },
{ stu_id = 103, stu_name = "deepu",
stu_dept = "mba", stu_salary = 8900 }};
Output :
{ stu_id = 101, stu_name = "bobby",
stu_dept = "cse", stu_salary = 8900 },
{ stu_id = 102, stu_name = "sravan",
stu_dept = "ece", stu_salary = 8900 },
{ stu_id = 103, stu_name = "deepu",
stu_dept = "mba", stu_salary = 8900 }};
Input :
{ stu_id = 101, stu_name = "bobby",
stu_dept = "cse", stu_salary = 8900 }
Output:
{ stu_id = 101, stu_name = "bobby",
stu_dept = "cse", stu_salary = 8900 }
方法
To display the list of students follow the following steps:
- Create a list of students with four variables(Id, name department and semester).
- Iterate through the student details by using for loop and get the student details by using select clause
- Display the student details.
例子 :
C#
// C# program to print the list of students
// details using select clause
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
class Student{
// Declare 4 variables - id, age, department and semester
int stu_id;
string stu_dept;
string stu_name;
int stu_semester;
// Get the to string method that returns
// id, age, department and semester
public override string ToString()
{
return stu_id + " " + stu_name + " " +
stu_dept + " " + stu_semester;
}
// Driver code
static void Main(string[] args)
{
// Declare a list variable
List stu = new List()
{
// Create 3 Student details
new Student{ stu_id = 101, stu_name = "bobby",
stu_dept = "CSE", stu_semester = 2 },
new Student{ stu_id = 102, stu_name = "sravan",
stu_dept = "ECE", stu_semester = 1 },
new Student{ stu_id = 103, stu_name = "deepu",
stu_dept = "EEE", stu_semester = 4},
};
// Iterate the Employee
// using select function
IEnumerable Query = from student in stu select student;
// Display student details
Console.WriteLine("ID Name Department Semester");
Console.WriteLine("+++++++++++++++++++++++++++");
foreach (Student e in Query)
{
// Call the to string method
Console.WriteLine(e.ToString());
}
}
}
输出:
ID Name Department Semester
+++++++++++++++++++++++++++
101 bobby CSE 2
102 sravan ECE 1
103 deepu EEE 4