Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to compare ReadOnlyMemory<T> instances?

Tags:

c#

The ReadOnlyMemory<T> and ReadOnlySpan<T> provide Equal(other) method but no CompareTo(other). I wonder if there a more efficient way to implement IComparable<ReadOnlyMemory<T>> other than a loop and compare each element. In my case T is either char or byte.

like image 629
Kirill Kovalenko Avatar asked Sep 06 '25 14:09

Kirill Kovalenko


1 Answers

There does not appear to be a native method of comparing ReadOnlyMemory instances. There are however native methods for ReadOnlySpan, which can be accessed by using the ReadOnlyMemory's .Span property:

ReadOnlyMemory<T> One = ...;
ReadOnlyMemory<T> Two = ...;

bool ContentsEqual = One.Span.SequenceEqual(Two.Span);
int Comparison = One.Span.SequenceCompareTo(Two.Span);

Enjoy :)

like image 79
Simon Mattes Avatar answered Sep 08 '25 06:09

Simon Mattes