Chace Fields
Chace Fields

Reputation: 907

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?

Upvotes: 5

Views: 22640

Answers (4)

TKharaishvili
TKharaishvili

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

Tim Schmelter
Tim Schmelter

Reputation: 460298

You can use FirstOrDefault:

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

demo

Upvotes: 8

C&#233;dric Bignon
C&#233;dric Bignon

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

J. Steen
J. Steen

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

Related Questions