Reputation: 907
I have a list: var strings = new List<string>();
My list contains 5 strings.
string.Add("Paul");
string.Add("Darren");
string.Add("Joe");
string.Add("Jane");
string.Add("Sally");
I want to iterate over the list and as soon as I find a string that begins with "J", I do not need to continue processing the list.
Is this possible with LINQ?
Upvotes: 5
Views: 22640
Reputation: 2099
Try:
strings.FirstOrDefault(s=>s.StartsWith("J"));
And also if you are new to LINQ I'd recommend going through 101 LINQ Samples in C#.
Upvotes: 14
Reputation: 460298
You can use FirstOrDefault
:
var firstMatch = strings.FirstOrDefault(s => s.StartsWith("J"));
if(firstMatch != null)
{
Console.WriteLine(firstMatch);
}
Upvotes: 8
Reputation: 13022
Using the First
LINQ method (in System.Linq
):
strings.First(e => e.StartsWith("J"));
Or FirstOrDefault
if you are not sure that any element in your list will satisfy the condition:
strings.FirstOrDefault(e => e.StartsWith("J"));
Then, it returns null
if no element has been found.
Upvotes: 3
Reputation: 15588
bool hasJName = strings.Any(x => x.StartsWith("J"));
This checks to see if any names that start with J exist.
string jName = strings.FirstOrDefault(x => x.StartsWith("J"));
This returns the first name that starts with J. If no names starting with J are found, it returns null
.
Upvotes: 3