2

I have a list of Strings.

How can I check if the list of Strings contains a string with the prefix 2#?

I saw this: Find substring in a list of strings

I tried the following:

if ((startId == item.ID.ToString())
       && (item.NextButtons.Contains(s => s.Contains("2#")))) ;
   {
     OK = false;
   }
Community
  • 1
  • 1
bandeee
  • 81
  • 1
  • 6

2 Answers2

6

If I understood correctly:

yourList.Any(s => s.Contains("2#"))

Use the LINQ Any method to determine if any element of a collections satisfies the condition.

The condition is a lambda method that takes each string element of your list as an input parameter and checks if it Contains the string "2#". It does this until the first one is found and then returns either true or false.

If you wanted to return the actual string, you would use the FirstOrDefault method instead of Any. It would then return either the string or null, if none are found.

edit: if the 2# has to be at the start of the string, see @Some1.Kill.The.DJ's answer.

Rotem
  • 21,452
  • 6
  • 62
  • 109
3

You want 2# in front of them..

So,it should be

yourList.Any(s => s.StartsWith("2#"));
                    -----------
Anirudha
  • 32,393
  • 7
  • 68
  • 89