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


You can use FirstOrDefault

:

var firstMatch = strings.FirstOrDefault(s => s.StartsWith("J"));
if(firstMatch != null)
{
    Console.WriteLine(firstMatch);
}

      



demonstration

+6


source


bool hasJName = strings.Any(x => x.StartsWith("J"));

      

This checks if there are any names starting with J.

string jName = strings.FirstOrDefault(x => x.StartsWith("J"));

      

This returns the first name that starts with J. If no names that start with J are found, it returns null

.

+2


source


Using First

LINQ Method (in System.Linq

):

strings.First(e => e.StartsWith("J"));

      

Or FirstOrDefault

, if you're not sure if any item in your list will satisfy the condition:

strings.FirstOrDefault(e => e.StartsWith("J"));

      

Then it returns null

if the item is not found.

+1


source







All Articles