简体   繁体   中英

How to find first occurrence in c# list without going over entire list with LINQ?

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?

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#.

You can use FirstOrDefault :

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

demo

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM