LINQ to String Array

LINQ to String Array means writing LINQ queries on a string array to get the required data. If we use LINQ queries on string arrays, we can quickly get the required elements without writing much code.

Syntax of LINQ to String Arrays

Following is the syntax of writing LINQ queries on string arrays to get the required elements from array collection.

 

C# Code

 

IEnumerable<string> result = from a in arr
                             select a;

VB.NET Code

 

Dim result As IEnumerable(Of String) = From a In arr

If you observe the above syntax, we wrote the LINQ query to get data from the “arr” string array.

Example of LINQ to String Array

Following is the example of LINQ to String Array to get elements from the string array sequence where the name starts with “S”.

 

C# Code

 

using System;
using System.Collections.Generic;
using System.Linq;

namespace Linqtutorials
{
  class Program
  {
    static void Main(string[] args)
    {
      string[] arr = { "Suresh", "Rohini", "Praveen", "Sateesh" };
      IEnumerable<string> result = from a in arr where a.ToLowerInvariant().StartsWith("s")
                                   select a;
      foreach (string item in result)
      {
        Console.WriteLine(item);
      }
      Console.ReadLine();
    }
  }
}

VB.NET Code

 

Module Module1
Sub Main()
Dim arr As String() = {"Suresh", "Rohini", "Praveen", "Sateesh"}
Dim result As IEnumerable(Of String) = From a In arr Where a.ToLowerInvariant().StartsWith("s")
For Each item As String In result
Console.WriteLine(item)
Next
Console.ReadLine()
End Sub
End Module

If you observe the above code, we used the LINQ query on the “arr” string array to get elements whose name starts with “s”. Here, we used ToLowerInvariant() property to convert string array elements to lowercase and compare because LINQ queries are case sensitive.

Result of LINQ to String Array Example

Following is the result of the LINQ to String Array Example.

 

Suresh
Sateesh

This is how we can use LINQ queries with string arrays to get the required data.