Christoph
Christoph

Reputation: 333

Check if string contains at least one part of an enum

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?

Upvotes: 1

Views: 3589

Answers (2)

Matthew Whited
Matthew Whited

Reputation: 22433

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));

Upvotes: 9

Andrew Diamond
Andrew Diamond

Reputation: 6335

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));

Upvotes: 2

Related Questions