I want to sort point3dcollection by x value. How I do that?
Solved! Go to Solution.
Solved by khoa.ho. Go to Solution.
Solved by norman.yuan. Go to Solution.
Since Point3dCollection is an IList and IEnumerable, you can sorted easily with System.Linq namespace methods. Here is an example:
[CommandMethod("SortPt")] public static void SortPoints() { Document dwg = CadApp.DocumentManager.MdiActiveDocument; Editor ed = dwg.Editor; Point3d[] pts = new Point3d[] { new Point3d(10.0,2.0,0.0), new Point3d(8.0,2.0,0.0), new Point3d(6.0,2.0,0.0), new Point3d(4.0,2.0,0.0), new Point3d(2.0,2.0,0.0), new Point3d(0.0,2.0,0.0), }; Point3dCollection col = new Point3dCollection(pts); IEnumerable<Point3d> sorted = SortPoint3dCollection(col); foreach (var p in sorted) { ed.WriteMessage("\nPoint.X={0}", p.X); } Autodesk.AutoCAD.Internal.Utils.PostCommandPrompt(); } private static IEnumerable<Point3d> SortPoint3dCollection(Point3dCollection points) { var pt = from Point3d p in points orderby p.X ascending select p; return pt; }
Norman Yuan
Using LINQ for IEnumerable type class is great. This code will work the same:
point3dCollection.Cast<Point3d>().OrderBy(point => point.X);
Agree. This is an implementation of your code using Array as an alternative to List.
public static Point3dCollection Sort(this Point3dCollection collection, bool descending = false) { Point3d[] points = collection.Cast<Point3d>().ToArray<Point3d>(); Array.Sort<Point3d>(points, delegate(Point3d point1, Point3d point2) { if (descending) { return point2.X.CompareTo(point1.X); // point2.X - point1.X } else { return point1.X.CompareTo(point2.X); // point1.X - point2.X } }); return new Point3dCollection(points); }
Hi just a little confused:
will the original point3dCollection be reordered or will one have to create a new ordered list.
e.g.
Do I have to do this:
Point3dCollection newOrderedList = point3dCollectionOldList.Cast<Point3d>().OrderBy(point => point.X);
EDIT: actually the above does not work It says that one cannot convert type system.linq.iOrderedEnumerable<autodesk.autocad.Geometry.Point3d> to <AutoDesk.Autocad.Geometry.Point3dCollection> any ideas on how to simply create a new list?
or will just doing this suffice to reorder the list:
point3dCollection.Cast<Point3d>().OrderBy(point => point.X);
rgds
BK
Hi,
Most Linq extension methods (as Cast and OrderBy) return an IEnumerable<T> lazy sequence.
If you need a classic collection as Point3d[] or List<Point3d> you'l have to convert the IEnumerable<Point3d> with the ToArray or ToList extension methods.
If you need a Point3dCollection, you can use the Point3dCollection constructor which requires an Point3d array as parameter.
try this way:
Point3dCollection newOrderedList = new Point3dCollection(
OldList .Cast<Point3d>() .OrderBy(point => point.X) .ToArray());