Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List.Any get matched String

Tags:

c#

lambda

linq

FilePrefixList.Any(s => FileName.StartsWith(s))

Can I get s value here? I want to display the matched string.

like image 936
Santhosh Nayak Avatar asked Aug 13 '15 09:08

Santhosh Nayak


3 Answers

Any determines only if there is a match, it doesn't return anything apart from the bool and it needs to execute the query.

You can use Where or First/FirstOrDefault:

string firstMastch = FilePrefixList.FirstOrDefault(s => FileName.StartsWith(s)); // null if no match

var allMatches = FilePrefixList.Where(s => FileName.StartsWith(s));
string firstMastch = allMatches.FirstOrDefault(); // null if no match

So Any is fine if all you need to know is if ther's a match, otherwise you can use FirstOrDefault to get the first match or null(in case of reference types).

Since Any needs to execute the query this is less efficient:

string firstMatch = null;
if(FilePrefixList.Any(s => FileName.StartsWith(s)))
{
    // second execution
    firstMatch = FilePrefixList.First(s => FileName.StartsWith(s));
}

If you want to put all matches into a separate collection like a List<string>:

List<string> matchList = allMatches.ToList(); // or ToArray()

If you want to output all matches you can use String.Join:

string matchingFiles = String.Join(",", allMatches);  
like image 92
Tim Schmelter Avatar answered Oct 16 '22 00:10

Tim Schmelter


Not with Any, no... that's only meant to determine whether there are any matches, which is why it returns bool. However, you can use FirstOrDefault with a predicate instead:

var match = FilePrefixList.FirstOrDefault(s => FileName.StartsWith(s));
if (match != null)
{
    // Display the match
}
else
{
    // Nothing matched
}

If you want to find all the matches, use Where instead.

like image 15
Jon Skeet Avatar answered Oct 15 '22 23:10

Jon Skeet


if FilePrefixList is a List<string>, you can use List<T>.Find method:

string first = FilePrefixList.Find(s => FileName.StartsWith(s));

fiddle: List.Find vs LINQ (Find is faster)

List<T>.Find (MSDN) returns the first element that matches the conditions defined by the specified predicate, if found; otherwise, the default value for type T

like image 3
ASh Avatar answered Oct 15 '22 22:10

ASh