Menu ▼

Previous Next

LINQ to String Array :

In this example we will write LINQ queries on string array to find string starting with specific letter, string containing specific letter and string length (digits) more than 4 .

LINQ Query :
Below LINQ query will find the months starting with "J" in the string array.

string[] ary = new string[] { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };

var res = from months in ary

            where months.StartsWith("J")

            select new { MonthStartWith_J = months };

gvMonths.DataSource = res;

gvMonths.DataBind();


Output :
MonthStartWith_J
Jan
Jun
Jul

LINQ Query :
Below LINQ query will find the months which contains "A" in the string array.

string[] ary1 = new string[] { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };

var month = from months in ary1

            where months.ToLowerInvariant().Contains("a")

            select new { MonthContains_A = months };

gvMonths1.DataSource = month;

gvMonths1.DataBind();


Output :
MonthContains_A
Jan
Mar
Apr
May
Aug

LINQ Query :
Below LINQ query will find the names which are having lenght more thatn 4 in the string array.

string[] ary2 = new string[] { "Ravi", "Ramana", "Brod", "Wess", "Vinay", "Smith", "Williams" };

var names = from name in ary2

            where name.Length > 4

            select new { NameMoreThan4Digits = name };

gvNames.DataSource = names;

gvNames.DataBind();


Output :
NameMoreThan4Digits
Ramana
Vinay
Smith
Williams

Previous Next




Search dotnetlearners.com