Does List.Contains(mystring) do a reference comparison or a value comparison? Eg 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 and following line to:
if (!thelist.Contains(value)) thelist.Add(value);
Thanks
IList<T>
uses Comparator<T>.Default
to do the comparisons, and in turn that compares by value for String
objects.
If you wanted to, you could move your items to an IDictionary<T, bool>
or something similar, where you can specify your IComparator
- specifying one that checks for reference. (even though in that case, you're better off with the foreach loop)
If you can use LINQ, you could create a statement there with a reference comparison, too.
From MSDN of List<T>.Contains
This method determines equality using the default equality comparer
EqualityComparer<T>.Default
for T, the type of values in the list.... The Default property checks whether type T implements the
IEquatable<T>
generic interface and if so returns anEqualityComparer<T>
that uses that implementation. Otherwise it returns anEqualityComparer<T>
that uses the overrides ofObject.Equals
andObject.GetHashCode
provided byT
.
Looking at reflector (and by the principle of least surprise), String Equality has value type semantics - so they are equal if they have the same strings. Both Equals(Object)
and IEquatable.Equals(T)
delegate to String::EqualsHelper
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With