简体   繁体   中英

List or Dictionary or something else?


I want to save some coordinates in a dictionary, BUT the xPos should be twice or more in the dictionary.

The problem is that the following exception appears:
ArgumentException: An element with the same key already exists in the dictionary.

How can I solve the problem ?

I allready thought that I can use a List or an Array, but I want a Key and a Value.

After I saved the coordinates in a Dict (or something else) I want to check whether a new coordinate is a certain distance of the existing ones.

The xPos is allways the same:
There is a "chart" where I place some blocks in a row with different yPos.
1. Block: xPos = 0, yPos = random
2. Block: xPos = 1, yPos = random
...
n. Block: xPos = 80, yPos = random
n+1. Block: xPos = 0, yPos = 20 + random

I have three iterations, for each 80 Blocks are placed.

在此处输入图片说明

SORRY for my bad english :|
I hope you could understand.

You can create a class (or a struct) to keep and use your coordinates, instead of a dictionary. The class can have Key and Value properties and also additional fields if needed.

You should save the values like List, where Position contains:

public int X { get; set; }
public int Y { get; set; }

Or you can use some another class/struct from C# or some 3rd libraries (2d vector, point, etc) depends on where you want to use it. :)

Or you can use List of Tuple to store list of int - int pairs without creating new class and without worrying about duplicate values :

.....
List<Tuple<int, int>> blocks = new List<Tuple<int, int>>();
blocks.Add(Tuple.Create(0, random));
blocks.Add(Tuple.Create(1, random));
.....

Since you're storing points in a 2-d surface and want to do nearest-point detection, I'd recommend using a Binary Space Partitioning (BSP) tree , such as a QuadTree. Here's a link to a quadtree implementation in C#.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM