C# Program to Find the List of Students whose Name Contains 4 Characters 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 contains 4 characters using Where() clause in LINQ. So to use Where() clause you need to add System.Linq and System.Collections.Generic namespaces in your program.
Syntax:
data.Where(student => student.Length == 4)
Example:
Input : [("bobby"),("srav"),("ramya"),("gopi"),("hari")("sai");] Output : [("srav"),("gopi"),("hari")] Input : [("bobby"),("ramya"),("sai");] Output : No Output
Approach
To print the list of students whose name contains 4 characters follow the following steps:
- Create a list
- Add the student names to the list
- Find the student names whose length is 4 by using data.Where(student => student.Length == 4)
- Display the student names
Example:
C#
// C# program to display the list of students whose // name contains four characters using Where() method using System; using System.Collections.Generic; using System.Linq; class GFG{ static void Main( string [] args) { // Define a list List< string > data = new List< string >(); // Add names into the list data.Add( "bobby" ); data.Add( "srav" ); data.Add( "ramya" ); data.Add( "gopi" ); data.Add( "hari" ); data.Add( "sai" ); // Choose the student whose name length is 4 // Using where clause IEnumerable< string > final = data.Where(student => student.Length == 4); Console.WriteLine( "Length 4 Details" ); // Display student names foreach ( string stname in final) { Console.WriteLine(stname); } } } |
Output:
Length 4 Details srav gopi hari
Please Login to comment...