Does List <String> .Contains (mystring) perform a reference comparison or comparison of values?
Does List.Contains (mystring) contain a reference comparison or a comparison of values? For example, I have this code:
/// <summary>
/// If the value isn't null or an empty string,
/// and doesn't exist in the list, it adds it to the list
/// </summary>
static void AddToListIfNotEmpty(List<string> thelist, SqlString val)
{
string value = val.ToString().Trim();
if (!string.IsNullOrEmpty(value))
{
bool found = false;
foreach (string x in thelist) if (x == value) found = true;
if (!found) thelist.Add(value);
}
}
Can I simplify the foreach line and the following line:
if (!thelist.Contains(value)) thelist.Add(value);
thank
IList<T>uses Comparator<T>.Defaultto perform comparisons and, in turn, compares values ββfor objects String.
If you want, you can transfer your elements to IDictionary<T, bool>or something similar, where you can specify your own IComparator- by specifying the one that checks the link. (although in this case you are better off with a foreach loop)
LINQ, .
, ( , complexity *), foreach, .
, :
static void AddToListIfNotEmpty(List<string> thelist, SqlString val)
{
string value = val.ToString().Trim();
if (value != string.Empty && !thelist.Contains(value))
thelist.Add(value);
}
, string.IsNullOrEmpty() null . Edit: , , SqlString.ToString() NULL SqlString "Null", , . , :
if (val.IsNull)
return;
Finally, returning to my comment on complexity: if you are dealing with a large number of elements, you can look HashSetinstead of using List(same namespace). It will not support the order of adding strings, but it Containsworks O (1) , while your current is O (n) .