1

Is there an easy way to check if a longer string contains one of the defined parts of an enum using C#

For example I've got the following enum:

enum myEnum
{
   this,
   is,
   an,
   enum
};

and I have such a string:

string myString = "here I have a sample string containing an enum";

since the string is containing the keyword enum I'd like to find this within the string.

so I would need a function like string.contains(myString,myEnum). This function should then ruturn true or false. Of course I could compare each value in the enum - but there might be an easier way...

How can I achieve this?

2 Answers 2

9

your emum...

public enum MyEnum
{
    @this,
    @is,
    an,
    @enum
}

... to check ...

var myString = "here I have a sample string containing an enum";
var found = Enum.GetNames(typeof(MyEnum)).Any(e=>myString.Contains(e));
Sign up to request clarification or add additional context in comments.

2 Comments

@ChrsitophH Our answers are the same, Matthew just beat me by 15 seconds.
To be fair yours also makes a list instead of just using the array from Enum.GetNames ;)
2

First, get all the string values of your enum

List<string> s = new List<string>(Enum.GetNames(typeof(myEnum)));

Then, check for existence!

s.Any(s=> myString.Contains(s));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.