find IndexOf one of few strings, regardless which in C#?

I want to find the first index of "class", "struct" or "interface" in text, I don't care which, is there a way to do this in one expression?

PS It seems to me this question should be asked allready, but I couldn't find such, I hope it's not...

Jon Skeet
people
quotationmark

I can think of two options here:

  • Regular expressions - fairly straightforward, but remember to quote the matches if you are accepting them as input. Sample code:

    using System;
    using System.Text.RegularExpressions;
    
    public class Test
    {
        public static void Main()
        {
            var regex = new Regex("(struct|class|interface)");
            var match = regex.Match("Hello, this contains a classic car");
            if (match.Success)
            {
                Console.WriteLine(match.Index);
            }
        }
    }
    
  • Normal IndexOf with LINQ

For the second option, here's an example:

// Adjust as you need to
private static int? FindFirstIndex(string text, string[] matches)
{
    return matches.Select(match => text.IndexOf(match))
                  .Where(index => index != -1)
                  .OrderBy(index => index)
                  .Select(index => (int?) index)                      
                  .FirstOrDefault();
}

That will return a null value if there are no matches. Note that it won't tell you which match was found. For that, you could use:

// Adjust as you need to
private static Tuple<string, int> FindFirstMatch(string text, string[] matches)
{
    return matches.Select(match => Tuple.Create(match, text.IndexOf(match))
                  .Where(tuple => tuple.Item2 != -1)
                  .OrderBy(tuple => tuple.Item2)
                  .FirstOrDefault();
}

Again, this will return null (but a reference this time rather than an int?) if it doesn't match anything.

people

See more on this question at Stackoverflow