C# Program to Find the List of Students whose Name Starts with ‘S’ using where() Method of List Collection using LINQ
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 whose name starts with ‘S’ using where() Method of List Collection. Here the where method filters the given sequence or array of values based on the predicate. To use the where() method you need to import System.Linq and System.Collections.Generic namespaces in your program.
Syntax:
Where<TSource>(IEnumerable<TSource>, Func<TSource, Boolean>)
Example:
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
Approach:
To find the list of students whose name starts with ‘S’ follow the following steps:
- Create a list of students with three variables(Id, name and age).
- Iterate through the student details by using Where() function and get the student details by choosing student name starts with’ S’ using s => s.name[0] == ‘S’.
- Now call the ToString() method.
- 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 id;
int age;
string name;
public override string ToString()
{
return id + " " + name + " " + age;
}
static void Main( string [] args)
{
List<Student> student = new List<Student>()
{
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 }
};
IEnumerable<Student> Query = student.Where(s => s.name[0] == 'S' );
Console.WriteLine( "ID Name Age" );
Console.WriteLine( "+++++++++++++" );
foreach (Student e in Query)
{
Console.WriteLine(e.ToString());
}
}
}
|
Output:
ID Name Age
+++++++++++++
101 Sravan 12
104 Sathwik 12
105 Saran 15
Last Updated :
24 Oct, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...