C# - Print names that contain a substring using LINQ

Learn, how to print the names that contain a substring using LINQ in C#? By Nidhi Last updated : April 01, 2023

Here, we will create an array of Names then we print only those names that contain "MAN" substring using LINQ and print them on the console screen.

C# program to print the names that contain 'MAN' substring using LINQ

The source code to print names that contain "MAN" substring using LINQ in C# is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

//Program to print the names that contain 
//"MAN" substring using LINQ in C#

using System;
using System.Linq;

class Demo {
  static void Main() {
    string[] Names = {"SUMAN","RAMAN","KIRAN","MOHAN"};

    var strs = from s in Names
    where s.Contains("MAN")
    select s;

    Console.WriteLine("Names are :");
    foreach(string str in strs) {
      Console.WriteLine("{0} ", str);
    }
  }
}

Output

Names are :
SUMAN
RAMAN
Press any key to continue . . .

Explanation

In the above program, we created a class Demo that contains the Main() method.

string []Names = {"SUMAN","RAMAN","KIRAN","MOHAN"};

In the Main() method we created an array of Names

var strs = from s in Names
    where s.Contains("MAN")
    select s;

In the above code, we select names that contain "MAN" substring.

Console.WriteLine("Names are :");
foreach (string str in strs)
{
    Console.WriteLine("{0} ",str);
}

In the above code, we printed the names selected from the LINQ query on the console screen.

C# LINQ Programs »





Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.