AlexC AlexC - 28 days ago 9
C# Question

How to retrieve the value passed in string.Contains method?

Is it possible to retrieve the value passed in the string.Contains method?

The usage scenario would be something like this:

foreach (string x in myList)
{
if (x.Contains("Salt") || x.Contains("Sugar") || x.Contains("Pepper"))
{
MessageBox.Show("The ingredient found in this line of myList is: " + //the ingredient found)
}
}


The objective is to AVOID having to repeat code. Right now I have to do the following to achieve the desired result:

foreach (string x in myList)
{
if (x.Contains("Salt"))
{
MessageBox.Show("The ingredient found in this line of myList is: Salt");
}

if (x.Contains("Sugar"))
{
MessageBox.Show("The ingredient found in this line of myList is: Sugar");
}

if (x.Contains("Pepper"))
{
MessageBox.Show("The ingredient found in this line of myList is: Pepper");
}
}


If it's not possible is there any alternative?

Thanks in advance!

Answer Source

You could use the FirstOrDefault LINQ extension method and write something like this:

string[] ingredients = { "Salt", "Sugar", "Pepper" };
foreach (string x in myList)
{
    string ingredient = ingredients.FirstOrDefault(x.Contains); // i.e., i => x.Contains(i)
    if (ingredient != null)
    {
        MessageBox.Show("The ingredient found in this line of myList is: " + ingredient);
    }
}

If that's a little too cryptic for you, then create an extension method with a descriptive name:

// Put this in a static class somewhere.
public static string FindAny(this string s, params string[] values)
{
    return values.FirstOrDefault(s.Contains);
}

And call it like this:

string ingredient = x.FindAny(ingredients);
// Or, at the expense of extra memory allocations, you could inline the array:
//   string ingredient = x.FindAny("Salt", "Sugar", "Pepper");
if (ingredient != null)
{
    MessageBox.Show("The ingredient found in this line of myList is: " + ingredient);
}

Note: To output multiple ingredients found in the same line, use Where instead of FirstOrDefault:

string[] ingredients = { "Salt", "Sugar", "Pepper" };
foreach (string x in myList)
{
    List<string> ingredientsFound = ingredients.Where(x.Contains).ToList();
    if (ingredientsFound.Count > 0)
    {
        MessageBox.Show("The ingredient(s) found in this line of myList are: " +
            string.Join(", ", ingredientsFound));
    }
}