check for string in list in csharp

To check if a string exists in a list of strings in C#, you can make use of the Contains method of the List class.

Here's a code snippet that demonstrates this:

main.cs
List<string> strings = new List<string> { "foo", "bar", "baz" };
string searchString = "bar";

bool stringExists = strings.Contains(searchString);

if (stringExists)
{
    Console.WriteLine("The string exists in the list.");
}
else
{
    Console.WriteLine("The string does not exist in the list.");
}
301 chars
14 lines

In this example, we create a List object containing a few strings. We then define a searchString variable with the string we are interested in finding. We use the Contains method to check if the string exists in the list, and store the boolean result in a stringExists variable. We then use an if statement to print out a message depending on whether the string exists in the list.

related categories

gistlibby LogSnag