check if string is in string[] c#
To check if a string is present in an array of strings in C#, you can use the Contains
method from the System.Linq
namespace. Here are the steps to do it:
- Import the System.Linq namespace: Before using the
Contains
method, you need to import theSystem.Linq
namespace. You can do this by adding the following line at the top of your C# file:
using System.Linq;
- Create an array of strings: Define an array of strings that you want to check for the presence of a specific string. For example:
string[] stringsArray = { "apple", "banana", "orange" };
- Use the Contains method: To check if a string is present in the array, you can use the
Contains
method. This method returns a boolean value indicating whether the array contains the specified string. For example:
string searchString = "banana";
bool isPresent = stringsArray.Contains(searchString);
In this example, the isPresent
variable will be true
because the string "banana" is present in the stringsArray
.
- Check the result: You can then use the
isPresent
variable to perform further actions based on whether the string is present or not. For example:
if (isPresent)
{
Console.WriteLine("The string is present in the array.");
}
else
{
Console.WriteLine("The string is not present in the array.");
}
This code will output "The string is present in the array." if the string is found in the array, or "The string is not present in the array." if it is not found.
By following these steps, you can check if a string is present in an array of strings in C#.