简体   繁体   中英

How to sort generic list?

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.

Use Enumerable.OrderBy :

List<ContainerData> dataOfPreviusImage = GetSomeData();
var sorted = dataOfPreviusImage.OrderBy(cd => cd.pointProperty.X);

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));

为了帮助您顺利进行,ContainerData类应实现IComparable和理想的IEquateable。

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