I've been looking for some efficient and precise way to check if a ReadOnlyMemory<char> in C# contains in a Hashset of ReadOnlyMemory or any other collection.
I saw some suggestions to convert to string, but I'd highly like to avoid it to enhance memory-efficiency. The only other way that I've found is to write the custom IEqualityComparer, but I'm also wondering if anyone has discovered a better solution.
You do indeed need a custom comparer. But don't
ToStringanything inside the comparer, that's inefficient.Instead use
EqualsonSpans that you create from theMemory. Also you can usestring.GetHashCodewhich has aSpanparameter.With the static
Instanceproperty, you also don't need to create it every time.