1

I need to make ascending sort of generic List. Here is my generic type:

public class ContainerData
{
   private Point pnt;
   private Size size;
   private Double Area;
   private Contour<Point> contour;

   public ContainerData()
   { }

   public ContainerData(ContainerData containerData)
   { 
     this.pnt=containerData.pnt;
     this.size=containerData.size;
     this.Area=containerData.Area;
     this.contour = containerData.contour;
   }

   public Point pointProperty
   {
       get
       {return pnt;}
       set
       {pnt = value;}
   }

   public Size sizeProperty
   {
       get
       {return size;}
       set
       {size = value;}
   }

   public Double AreaProperty
   {
       get
       {return Area;}
       set
       {Area = value;}
   }
   public Contour<Point> ContourProperty
   {
       get
       {return contour;}
       set
       { contour = value; }
   }
}

The ascending sorting have to be made under the value of X coordinate of th Point type.

Here is the class member that sholud be sorted:

 private List<ContainerData> dataOfPreviusImage;

Any idea how can I implement it?

Thank you in advance.

Michael
  • 13,950
  • 57
  • 145
  • 288
  • 2
    What have you tried? Is [`List.Sort`](http://msdn.microsoft.com/en-us/library/3da4abas.aspx) that difficult to find? – Jon Oct 11 '12 at 08:12
  • 1
    If you dont want to use LINQ I suggest you to read this msdn page: http://msdn.microsoft.com/en-us/library/w56d4y5z.aspx – Gianni B. Oct 11 '12 at 08:13
  • You can also look into this [link](http://stackoverflow.com/questions/289010/c-sharp-list-sort-by-x-then-y/) also – Neeraj Kumar Gupta Oct 11 '12 at 08:24

3 Answers3

9

Use Enumerable.OrderBy :

List<ContainerData> dataOfPreviusImage = GetSomeData();
var sorted = dataOfPreviusImage.OrderBy(cd => cd.pointProperty.X);
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
Antonio Bakula
  • 20,445
  • 6
  • 75
  • 102
2

Make a Compare Function :

private int SortFunction(ContainerData obj1, ContainerData obj2)
{
    return obj1.pointProperty.X.CompareTo(obj2.pointProperty.X);
}

And call it like this:

dataOfPreviusImage.Sort(new Comparison<ContainerData>(SortFunction));
abc
  • 2,285
  • 5
  • 29
  • 64
1

To help you along your way, your ContainerData class should implement IComparable and ideally IEquateable as well.

onefootswill
  • 3,707
  • 6
  • 47
  • 101