### Author Topic: Double comparison  (Read 176 times)

0 Members and 1 Guest are viewing this topic.

#### latour_g

• Newt
• Posts: 120
##### Double comparison
« on: June 29, 2017, 09:57:28 am »
I would like to sort a list base on two values.  Is it possible to add another compare in my class BlkFleche ?
I need the list to be sort base on the X and then base on the Y, those are from coordinates.

So if I have my X and Y like that :
[10,1]
[4,6]
[9,2]
[10,4]
[4,2]
[10,6]

I would like the end result to be :
[4,2]
[4,6]
[9,2]
[10,1]
[10,4]
[10,6]

I'm using a list because I need to keep data in relation with the coordinates.

Code - C#: [Select]
`public class blkFleche : IComparable<blkFleche>{    public double positionX { get; set; }    public double positionY { get; set; }    public string attNOCABLE { get; set; }    public string attNOFIBRE { get; set; }     public int CompareTo(blkFleche other)    {        return this.positionX.CompareTo(other.positionX);    }} private void btnRead(){      List<blkFleche> listBlkSort = new List<blkFleche>();      //...      blkFleche blkNew = new blkFleche();      //...      blkNew.positionX = blkRef.Position.X;      blkNew.positionY = blkRef.Position.Y;      //...      listBlkSort.Add(blkNew);      //...      listBlkSort.Sort();}`

#### Jeff H

• Needs a day job
• Posts: 5853
##### Re: Double comparison
« Reply #1 on: June 29, 2017, 10:11:27 am »
I might have a chance later to create an example, but LINQ has ThenBy that you could use.
https://msdn.microsoft.com/en-us/library/bb534743(v=vs.110).aspx

#### gile

• Water Moccasin
• Posts: 2089
• Marseille, France
##### Re: Double comparison
« Reply #2 on: June 29, 2017, 10:57:53 am »
Hi,

You can implement IComparable<blkFleche> this way:

Code - C#: [Select]
`    public class blkFleche : IComparable<blkFleche>    {        public double positionX { get; set; }        public double positionY { get; set; }        public string attNOCABLE { get; set; }        public string attNOFIBRE { get; set; }         public int CompareTo(blkFleche other)        {            int compareX = this.positionX.CompareTo(other.positionX);            return compareX == 0 ? this.positionY.CompareTo(other.positionY) : compareX;        }    }`

But as Jeff said, you can directly use linq extension methods:

Code - C#: [Select]
`List<blkFleche> listBlk = new List<blkFleche>(); // fill the listBlk List<blkFleche> listBlkSort = listBlk    .OrderBy(blk => blk.positionX)    .ThenBy(blk => blk.positionY)    .ToList();`

Or, more efficiently, if you do not absolutely need a List<blkFleche>:

Code - C#: [Select]
`IEnumerable<blkFleche> listBlkSort = listBlk    .OrderBy(blk => blk.positionX)    .ThenBy(blk => blk.positionY);`
Speaking English as a French Frog

#### latour_g

• Newt
• Posts: 120
##### Re: Double comparison
« Reply #3 on: June 29, 2017, 04:14:42 pm »
Great, thank you both !