Implementing IEqualityComparer for custom object comparison

I had a simple snippet of code:


foreach (var muscle in muscles)
{
var currentMuscle = new ExerciseGroup(muscle.Name, muscle.Name);

var foundMuscles = from e in ModelExercises
where e.PrimaryMuscles.Contains(muscle)
select e;
currentMuscle.AddRange(foundMuscles);
GroupedExercises.Add(currentMuscle);
}

However where e.PrimaryMuscles.Contains(muscle) refused to generate any results. To me, it was logical that the muscles are the same (they Shared and ID and a Name), but to the compiler they were different. Obviously, they were equal in properties but not the same object… Silly me. So the problem is stated the stage is set.

Thankfully .Contains() has an overload that takes two parameters an object and an IEqualityComparer, great! Let’s get implementing!


private IEqualityComparer<Muscle> _compareMuscle { get; set; } = new MuscleComparer();

private class MuscleComparer : IEqualityComparer<Muscle>
{
public bool Equals(Muscle x, Muscle y)
{
bool id=false;
bool name=false;
if (x.Id == y.Id)
id = true;
if (x.Name == y.Name)
name = true;
return id && name;
}

public int GetHashCode(Muscle muscle)
{
int hCode = muscle.Id ^ muscle.Name.Length;
return hCode.GetHashCode();
}
}

So a very simple interface of two methods Equals and GetHashCode quick implementation and now our app returns a proper segmented view:

Perfect, it does, however, take a performance hit after this change (the load takes ~2seconds) so I might want to look at making it faster somehow.