Use linq to check if an string value is in string array or List in C#

19,975

Solution 1

Do you mean a Linq method?

If so, there is one:

Names.Contains(target)

Note there is no need for any lambda here.

Solution 2

   Names.Any( s => s == target );

Solution 3

Something like this?

Names.Any(n => Equals(n, target));
Share:
19,975
Saeid
Author by

Saeid

Updated on June 04, 2022

Comments

  • Saeid
    Saeid almost 2 years

    I use the followings to check the array or List is Included a value:

    string[] Names= { /* */};
    string target = "";
    
    if(Array.IndexOf(Names, target) > -1)
      //Do
    

    So is there any linq command to check it?

  • Falanwe
    Falanwe about 12 years
    @Killercam : actually, I suspect the compiler would generate the same IL as Names.Any( s => s == target ) because there is no better way to find a match in an Array. If Names was not an array but some other kind of IEnumerable with a more efficient search algorithm, contains would be more efficient indeed.