1

I have a string array for example:

string[] myStrings = {"I want to take this string","This is not interesting"}

I want to check the string array if it contains a value and then return the entire string that contains it.

Example:

var index = Array.FindIndex(stringArray, x => x == stringArray.Contains("want"));

After this I want to return the string: I want to take this string since this contains the keyword I searched for.

How can I archieve this result?

4 Answers 4

10

I would use LINQ instead:

IEnumerable<string> occurences = stringArray.Where(s => s.Contains("want"));

In occurences you have the complete strings of all occurences which did match. You can do FirstOrDefault on it if you are just interested in the first hit.

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

Comments

3

You can also use Array.FindIndex as you've already tried, but then use this:

int index = Array.FindIndex(myStrings, str => str.Contains("want"));
string desired = index >= 0 ? myStrings[index] : null; 

1 Comment

Thanks for the help
2

Try this:

myStrings.FirstOrDefault(str => str.Contains("want"));

This will return the first string that contains want or null if it was not found. If you want a List of all the strings that contain want then replace FirstOrDefault with Where

1 Comment

Thanks for the help.
1
public string GetStringContent()
{
    string[] myStrings = { "I want to take this string", "This is not interesting" };
    string strContent=string.Empty;
    for (int i = 0; i < myStrings.Length; i++)
    {
        if (myStrings[i].Contains("want"))
        {
           return  myStrings[i];
        }
    }
    return strContent;
} 

Try This... It will return first string if it contains 'want'.

1 Comment

Instead of keep on looping, you could simply return or break if you are only interested in the first (or last in your case).

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.