Best Approach for a NativeHash that needs multiple entries?

My use case is a 2d map referenced by int2. I need to store an entity reference at a given position on the map so I would normally use a NativeHashMap<int2, Entity>. I do this for fast lookup(O(1)). However I want to support multiple entities per location. I would really need something like NativeHashMap<int2, NativeArray> but we can’t do that.

So as alternate I was thinking about a shared component that would be attached to these Entities ie:
struct MapLocation : ISharedComponentData
{
public int2 location;
}

This would allow me to use an EntityQuery with a filter applied. I think this would be fast possibly a good alternative but it will mean 100s maybe 1000s of entities that have different MapLocations (SharedComponentData). That means 100s or 1000s of archetypes. I am not sure that this won’t have even more issues. Maybe its better if I just do the O(n^2) comparison (all map locations versus all moving items that need to check all map locations). However if adding a ISharedComponentData is more like indexing a database, I certainly wouldn’t think twice about doing this.

The entities with MapLocation won’t move often if at all once in place. Does anyone have good experience as to what the best practice is for this case?

NativeMultiHashMap is like a NativeHashMap or a NativeArray, except that the values aren’t ordered (AFAIK): Struct NativeMultiHashMap<TKey, TValue> | Collections | 0.12.0-preview.13

If your map is immutable, a packed array of Entities and a NativeHashMap<int2, int2> is pretty optimal. Otherwise there’s NativeMultiHashMap, NativeHashMap of UnsafeList, and NativeHashMap<int2, Entity> where the Entity is an entity with a dynamic buffer holding more entities.

Fantastic, these are great solutions. I didn’t even know NativeMultiHashMap existed, thanks for that. The idea of spawning another entity with a buffer to act a list is one that should have occurred to me. Great info, thanks again.