List<string> SampleList = new List<string>();
string tmpStr = "MyStringValue";
From this example, how to check the value of the string variable tmpStr if it's already in SampleList?
List<string> SampleList = new List<string>();
string tmpStr = "MyStringValue";
From this example, how to check the value of the string variable tmpStr if it's already in SampleList?
You could use the List<T>.Contains Method
if (SampleList.Contains(tmpStr))
{
// list already contains this value
}
else
{
// the list does not already contain this value
}
If your objective is to prevent your list from containing duplicate elements at all times then you might consider using the HashSet<T> Class which does not allow for duplicate values.
Any particular reason for using List?
You can use a Set, Set<string> hs = new HashSet<string>(); and it will not allow duplicates.
Set<string> hs = new HashSet<string>();
hs.add("String1");
hs.add("String2");
hs.add("String3");
// Now if you try to add String1 again, it wont add, but return false.
hs.add("String1");
If you do not want duplicates for case insensitive elements use
HashSet<string> hs = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
Hope that helps.