Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Indexing a Dictionary with a Span

Tags:

c#

Suppose I have a Dictionary indexed with a string array:

new Dictionary<string[], T>(new CustomComparer())

I would like to use a Span to index into the dictionary without copying it to an array first.

Is there a way to achieve this? I can't do

new Dictionary<Span<string>, T>(new CustomComparer())

Neither can I use IReadonlyCollection as Span does not implement any interfaces.

like image 522
Sergey Slepov Avatar asked Oct 28 '25 14:10

Sergey Slepov


1 Answers

There is no way to use System.Collections.Generic with Span. Dictionary and other data structures from System.Collections.Generic are allocated on the heap, while Span is a ref struct and is allocated on the stack. The compiler won't allow it.

As an alternative, you can write your own stack-based dictionary/hash map implementation, using Span<string> for keys.

like image 189
Vlad Radu Avatar answered Oct 30 '25 05:10

Vlad Radu