Reputation: 1215
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?
Upvotes: 1
Views: 717
Reputation: 11
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'.
Upvotes: 1
Reputation: 156948
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.
Upvotes: 10
Reputation: 460068
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;
Upvotes: 3
Reputation: 37798
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
Upvotes: 2