7

How to find whether a string array contains some part of string? I have array like this

String[] stringArray = new [] { "[email protected]", "[email protected]", "@gmail.com" };
string str = "[email protected]"

if (stringArray.Any(x => x.Contains(str)))
{
    //this if condition is never true
}

i want to run this if block when str contains a string thats completely or part of any of array's Item.

2 Answers 2

22

Assuming you've got LINQ available:

bool partialMatch = stringArray.Any(x => str.Contains(x)); 

Even without LINQ it's easy:

bool partialMatch = Array.Exists(stringArray, x => str.Contains(x));

or using C# 2:

bool partialMatch = Array.Exists(stringArray,
      delegate(string x) { return str.Contains(x)); });

If you're using C# 1 then you probably have to do it the hard way :)

Sign up to request clarification or add additional context in comments.

1 Comment

Jon's code works fine here. You're missing something from your example.
0

If you're looking for if a particular string in your array contains just "@gmail.com" instead of "[email protected]" you have a couple of options.

On the input side, there are a variety of questions here on SO which will point you in the direction you need to go to validate that your input is a valid email address.

If you can only check on the back end, I'd do something like:

emailStr = "@gmail.com";
if(str.Contains(emailStr) && str.length == emailStr.length)
{
  //your processing here
}

You can also use Regex matching, but I'm not nearly familiar enough with that to tell you what pattern you'd need.

If you're looking for just anything containing "@gmail.com", Jon's answer is your best bets.

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.