List<string> SampleList = new List<string>();
string tmpStr = "MyStringValue";
tmpStr
从这个例子中,如果字符串变量已经存在,如何检查它的值SampleList
?
List<string> SampleList = new List<string>();
string tmpStr = "MyStringValue";
tmpStr
从这个例子中,如果字符串变量已经存在,如何检查它的值SampleList
?
if (SampleList.Contains(tmpStr))
{
// list already contains this value
}
else
{
// the list does not already contain this value
}
如果您的目标是防止列表始终包含重复元素,那么您可以考虑使用HashSet<T> Class
which 不允许重复值。
使用的任何特殊原因List
?
您可以使用 Set,Set<string> hs = new HashSet<string>();
它会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");
如果您不想重复不区分大小写的元素,请使用
HashSet<string> hs = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
希望有帮助。