Reputation: 9424
I have an 2D array like this:
string[,] arr=
{
{"1","ali"},
{"2","mehdi"},
{"3","john"},
{"4","milad"},
};
i search name in 2nd column by for statement like this:
string name="";
for (int i = 0; i < arr.GetUpperBound(0); i++)
{
if (arr[i, 1].StartsWith("m"))
{
name = arr[i, 1];
break;
}
}
Response.Write(name);
i want use LINQ instead of for statement to get the first name that start with 'm'.
how to convert above for statement to LINQ.
Upvotes: 2
Views: 559
Reputation: 125650
var name = arr.Cast<string>()
.Where((x, i) => i % 2 == 1 && x.StartsWith("m"))
.First();
i % 2 == 1
will take only items from second column and x.StartWith("m")
will take only names that start with 'm'
.
And you have to use Cast<string>()
before other LINQ methods, because multidimensional arrays does not implement generic IEnumerable<T>
.
Upvotes: 4