I would strongly recommend to not implement IEquatable<string>
, cause especially when working with collections, dictionaries, LINQ, etc. you don't really know when one of these methods will be called somewhere deep inside which leads maybe to subtle bugs.
Due to the fact that you like to compare two objects of different types a simple Comparer<T>
wouldn't work also.
So either write a TypeConverter
which converts your object into the desired type (in your case a string
) or add a method to your object like .ToEquatableString()
and use their output to compare your object with the other string.
Here is an example on you could get all elements, that match one of a string in another collection:
IEnumerable<String> otherElements = new[] {"abc", "def", "ghi" };
IEnumerable<ObjectA> myObjects = GetObjects();
var matchesFound = otherElements.Join( // Take the first collection.
myObjects, // Take the second collection.
s => s, // Use the elements in the first collection as key (the string).
obj => obj.ToEquatableString(), // Create a string from each object for comparison.
(s, obj) => obj, // From the matching pairs take simply the objects found.
StringComparer.OrdinalIgnoreCase); // Use a special string comparer if desired.