I have this class (a partial listing):
class CiscoSwitch
{
private string _SwitchName = string.Empty;
public SwitchName {get {return _SwitchName;} set{_SwitchName=value; }}
}
I have 2 lists of CiscoSwitch objects. I am trying to compare them to pick out the ones that are not duplicates. I only want the duplicates. I tried a Lambda expression but got a compiler error that CiscoSwitch was a non-delgate type.
I am now wondering about something like this – it would allow me to use the List.Except() method (I think):
static class SwitchComparer
{
static bool CompareSwitchNames(CiscoSwitch s1, CiscoSwitch s2)
{
if (sw1.SwitchName == s2.SwitchName) {return true;}
else {return false;}
}
}
// to find the differences
// this is a method of the CiscoSwitchClass
private List<CiscoSwitch> FindDifferences(List<CiscoSwitch> List1, List<CiscoSwitch> List2)
{
return List1.Except(List2, SwitchComparer.CompareSwitchNames();
}
this could also be done with a foreach but I think this way is a lot cleaner, if it is correct. I am also thinking there are other attributes of a CiscoSwitch I might want to compare some day so could add methods to the SwitchComparer class as I need them.
No, just having a single method like that won’t help you. You need to implement an
IEqualityComparer<CiscoSwitch>to pass toEnumerable.Except– and even then your code would need to be:Overriding
EqualsandGetHashCodewithinCiscoSwitchwill do the trick more naturally though – and ideally you should implementIEquatable<CiscoSwitch>too.However, it’s worth noting that mutable types like this don’t play terribly nicely with things like
Dictionary<,>– if you change an object in a way which affects its hash code after you’ve inserted it as a key into the dictionary, you won’t be able to get at it again. Consider making the type immutable if you can.A couple of other points to note:
Any time you write:
you should instead write the far simpler:
So your
CompareSwitchNamesmethod would be:static bool CompareSwitchNames(CiscoSwitch s1, CiscoSwitch s2)
{
return s1.SwitchName == s2.SwitchName;
}
Your parameter names for
FindDifferencesshould follow .NET naming conventions (e.g.list1andlist2)Exceptwill only find you the elements in the first list which aren’t in the second list; if you need to find the symmetric difference, consider usingHashSet<T>explicitly.EDIT: If you wanted to have multiple ways of comparing, you could have something like: