How can I find the first occurrence in a C # list without iterating over the entire list using LINQ?
I have a list: var strings = new List<string>();
My list contains 5 lines.
string.Add("Paul");
string.Add("Darren");
string.Add("Joe");
string.Add("Jane");
string.Add("Sally");
I want to iterate over a list and once I find a line starting with "J" I don't have to continue processing the list.
Is this possible with LINQ?
+3
source to share
4 answers
Try:
strings.FirstOrDefault(s=>s.StartsWith("J"));
And also if you are new to LINQ, I would recommend going through 101 LINQ Samples in C #.
+11
source to share
You can use FirstOrDefault
:
var firstMatch = strings.FirstOrDefault(s => s.StartsWith("J"));
if(firstMatch != null)
{
Console.WriteLine(firstMatch);
}
+6
source to share