I have a list of joints
List<Joint> joints = new();
The Joint class looks like this:
class Joint
{
private Node node1, node2;
private int weight;
public Joint(Node node1, Node node2)
{
this.node1 = node1;
this.node2 = node2;
weight = GetWeight();
}
private int GetWeight()
{
return (int)Math.Sqrt
((int)Math.Pow(node1.GetX() - node2.GetX(), 2) +
(int)Math.Pow(node1.GetY() - node2.GetY(), 2));
}
}
I would like to sort the joints list based on the weight value it contains. Preferably in only a few lines
>Solution :
To sort List<i> in place, all you need is Sort method:
joints.Sort((a, b) => a.GetWeight().CompareTo(b.GetWeight()));
Note, that you may want to make GetWeight method being public. An alternative is to make Joint being comparable:
public class Joint: IComparable<Joint> {
...
public int CompareTo(Joint other) {
if (other == null)
return 1;
return GetWeight().CompareTo(other.GetWeight());
}
}
if Joint is comparable, you can put just
joints.Sort();