Incognito
Incognito

Reputation: 455

Check string for an array item and match it

I have a string and an array and i want to check the string and find if the string contains any string from the array.

My array will contain about 10 elements max.

string[] stringArray = { "apple", "banana", "orange" };
string text="I want an apple";

public static string getItem(string text)
{
    //check text for stringArray items
    //return item (apple, banana, orange)
}
string item = getItem(text);

So what im looking for is to create a method that returns the item from. Also i'd like to know if there any alternatives ways to do this with Enum or List<>.

Finally i made my method like this

public static string getItem(string text)
        {
            string[] stringArray = { "Apple", "Banana", "Orange" };
            string item = stringArray.Where(s => text.ToUpper().Contains(s)).DefaultIfEmpty("None").FirstOrDefault();;
            return item;
        }

Upvotes: 1

Views: 4068

Answers (2)

PiousVenom
PiousVenom

Reputation: 6908

Instead of your array, you can make it a List<string>. And then in your getItem(), you can do:

List<string> stringList; // populate how you see fit
string text="I want an apple";

public static string getItem(string text)
{
    foreach(var s in stringList)
    {
        if(text.Contains(s))
        {
            // do stuff here
        }
    }
}

A List<> isn't required for the foreach loop. It's just nice to have.

Upvotes: 1

Justin Niessner
Justin Niessner

Reputation: 245399

With just a bit of LINQ-iness, this because quite easy:

return stringArray.Where(s => text.Contains(s)).FirstOrDefault();

This assumes that you want to return only the first matched string and that you want to do a case-sensitive comparison. If not, minor modifications can be made relatively easily to change things.

The code above will also work equally as well if your source is a List<string> as well (actually, anything that implements IEnumerable<string> will work in its place). An Enum, on the other hand, is not the proper fit for this kind of thing.

Upvotes: 6

Related Questions