C#中如何基于Joint对象的weight字段对列表进行排序?
解决方案
首先,你的Joint类中weight是私有字段,外部无法直接访问,所以需要先添加一个公共只读属性来暴露它:
class Joint { private Node node1, node2; private int weight; public Joint(Node node1, Node node2) { this.node1 = node1; this.node2 = node2; weight = GetWeight(); } // 新增公共属性暴露weight值 public int Weight => weight; private int GetWeight() { return (int)Math.Sqrt ((int)Math.Pow(node1.GetX() - node2.GetX(), 2) + (int)Math.Pow(node1.GetY() - node2.GetY(), 2)); } }
接下来提供两种极简的排序实现方式:
方式1:原地修改原列表排序
使用List<T>.Sort方法,传入lambda比较器,一行代码完成:
// 升序排序 joints.Sort((j1, j2) => j1.Weight.CompareTo(j2.Weight)); // 如需降序,调换比较顺序即可 joints.Sort((j1, j2) => j2.Weight.CompareTo(j1.Weight));
方式2:生成新的排序后列表(不改动原列表)
借助LINQ的OrderBy方法,同样一行代码搞定:
// 升序生成新列表 var sortedJoints = joints.OrderBy(j => j.Weight).ToList(); // 降序则用OrderByDescending var sortedJoints = joints.OrderByDescending(j => j.Weight).ToList();
内容的提问来源于stack exchange,提问作者callumetheridge
相关产品推荐
相关产品推荐

