Open In App

C# Program to Print the Names that Contain ‘MAN’ Substring Using LINQ

Last Updated : 06 Mar, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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 those names contains ‘MAN’ substring from the given array using LINQ. So to do our task we use Contains() method in the Where() method. 

Syntax:

Where(employee => employee.Contains("MAN"))

Here, the Contains() method is used to check whether the given string contains the “MAN” word in it or not, and then the Where() method filters the array accordingly. 

Example:

Input  : [("MANVITHA"),("SRIMANTH"),("RAVI"),("MANASA"),("MOUNIKA")("MANAS");]
Output : [("MANVITHA"),("SRIMANTH"),("MANASA"),("MANAS")]

Input  : [("bobby"),("ramya"),("sairam");]
Output : No Output

Approach

To print the list of  names contains “MAN” as a substring follow the following steps:

  1. Create a list(i.e., XEmployee) that will holds the name of the employees.
  2. Add the names to the list.
  3. Now find the names whose contains “MAN” as a substring by using XEmployee.Where(employee => employee.Contains(“MAN”))
  4. Display the employee names.

Example:

C#




// C# program to display those names that
// contain 'MAN' substring
using System;
using System.Collections.Generic;
using System.Linq;
 
class GFG{
 
static void Main(string[] args)
{
     
    // Define a list
    List<string> XEmployee = new List<string>();
     
    // Add names into the list
    XEmployee.Add("MANVITHA");
    XEmployee.Add("SRIMANTH");
    XEmployee.Add("RAVI");
    XEmployee.Add("MANASA");
    XEmployee.Add("MOUNIKA");
    XEmployee.Add("MANAS");
 
    // Choose the employee's name that
    // contains MAN as a sub string
    IEnumerable<string> final = XEmployee.Where(
                                employee => employee.Contains("MAN"));
 
    Console.WriteLine("Names that contain MAN substring:");
     
    // Display employee names
    foreach (string stname in final)
    {
        Console.WriteLine(stname);
    }
}
}


Output

Names that contain MAN substring:
MANVITHA
SRIMANTH
MANASA
MANAS


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads