2

enter image description here

I'm saving coordinate values in the HashSet.

And I want to sort it in order in the picture above.

Below is a typical point structure, using a Hashset.

struct Point
{
    public int x, y;
    public Point(int x, int y)
    {
        this.x = x;
        this.y = y;
    }
}

private HashSet<Point> hashset = new HashSet<Point>();

I found a source that just sort one value.

However, i have not found a source that sort two or coordinates values.

Give me an example of how to sort the coordinates.

SamSic
  • 347
  • 1
  • 4
  • 15
  • How do you want points within a given quadrant to be ordered? – Roger Lipscombe May 07 '19 at 12:02
  • 4
    HashSets have no order, which means it doesn't matter whether you use a HashSet or an array to store the values. Do you want to *store* the values in a specific sort order (in which case you'll have to use a different container) or read them in a specific order? In that case you could use LINQ and any container that allows sorting with `Comparer` argument, and use a custom comparer – Panagiotis Kanavos May 07 '19 at 12:06
  • and for a set that conserve order https://stackoverflow.com/questions/1552225/hashset-that-preserves-ordering – xdtTransform May 07 '19 at 12:42
  • Actually HashSet does have an order since you can use it as IEnumerable and it does maintain order in reality, but it's not a behaviour that one can depend on since it's not guaranteed and of course it's not a good idea anyway to do that :) – Ilya Chernomordik May 07 '19 at 13:30
  • @IlyaChernomordik But is unlikely to be insertion order and will possibly be completely different after adding an item. – spender May 07 '19 at 18:07
  • I think it actually is, at least looked like that in my examples, but it's of course just a curiosity not a call to action :) – Ilya Chernomordik May 07 '19 at 19:28

2 Answers2

2

You can use custom comparer to achieve what you want, where you can define your own rules:

var comparer = Comparer<Point>.Create((p1, p2) =>
{
    if (p1.y < p2.y)
    {
       return p1.x > p2.x ? 1 : -1;
    } 
    else
    {
       return p1.x < p2.x ? 1 : -1;
    }
});

hashset.OrderBy(p => p, comparer)

P.S. Not 100% sure that all the conditions are correct, but you get the idea I hope, so that you can write the logic you want following this example.

Ilya Chernomordik
  • 27,817
  • 27
  • 121
  • 207
1
points.OrderBy(p => Math.Atan2(p.y, p.x))

should do the trick.

It will order the points by their direction, measured from origin (i.e. starting from "west" in a clockwise direction)

If you're hoping to maintain that order in a set based structure, you'll need to think again because HashSet<T> has no implicit ordering.

spender
  • 117,338
  • 33
  • 229
  • 351