C# Program to Display the Student Details Using Select Clause LINQ
Last Updated :
24 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 learn how to print the list of students along with their details using a select clause in LINQ. The Select clause is used when we want to select some specific value from the given collection.
Syntax:
IEnumerable<Student> Query = from student in stu select student;
Example:
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 }
Approach
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.
Example :
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
class Student{
int stu_id;
string stu_dept;
string stu_name;
int stu_semester;
public override string ToString()
{
return stu_id + " " + stu_name + " " +
stu_dept + " " + stu_semester;
}
static void Main( string [] args)
{
List<Student> stu = new List<Student>()
{
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},
};
IEnumerable<Student> Query = from student in stu select student;
Console.WriteLine( "ID Name Department Semester" );
Console.WriteLine( "+++++++++++++++++++++++++++" );
foreach (Student e in Query)
{
Console.WriteLine(e.ToString());
}
}
}
|
Output:
ID Name Department Semester
+++++++++++++++++++++++++++
101 bobby CSE 2
102 sravan ECE 1
103 deepu EEE 4
Share your thoughts in the comments
Please Login to comment...