如何排序通用列表?

时间:2012-10-11 08:09:42

标签: c# .net list

我需要制作升序式的通用List。 这是我的通用类型:

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

升序排序必须在Point类型的X坐标值下进行。

这是sholud要分类的类成员:

 private List<ContainerData> dataOfPreviusImage;

知道如何实施它?

提前谢谢。

3 个答案:

答案 0 :(得分:9)

使用Enumerable.OrderBy

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

答案 1 :(得分:2)

制作比较功能:

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

并称之为:

dataOfPreviusImage.Sort(new Comparison<ContainerData>(SortFunction));

答案 2 :(得分:1)

为了帮助您,您的ContainerData类应该实现IComparable,并且理想情况下也适用于IE。