Skip to content
Related Articles
Open in App
Not now

Related Articles

C# Program to Find the List of Students whose Name Contains 4 Characters Using Where() Method of List Collection using LINQ

Improve Article
Save Article
  • Last Updated : 01 Nov, 2021
Improve Article
Save Article

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:

  1. Create a list
  2. Add the student names to the list
  3. Find the student names whose length is 4 by using data.Where(student => student.Length == 4)
  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

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!