Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sort a list of objects based on an integer of the object field c#

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading