C# Program to Print the Names that Contain ‘MAN’ Substring 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 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:
- Create a list(i.e., XEmployee) that will holds the name of the employees.
- Add the names to the list.
- Now find the names whose contains “MAN” as a substring by using XEmployee.Where(employee => employee.Contains(“MAN”))
- 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); } } } |
Names that contain MAN substring: MANVITHA SRIMANTH MANASA MANAS
Please Login to comment...