pav

pav

  • NA
  • 6
  • 0

Using IComparable for custom objects

Jul 29 2012 4:25 PM
I want to be able to arrange the following list from
BEFORE SORT
Relationship Item A: 3 B: 4
Relationship Item A: 4 B: 5
Relationship Item A: 7 B: 3
Relationship Item A: 1 B: 7
Relationship Item A: 5 B: 6
Relationship Item A: 2 B: 1

to

AFTER SORT
Relationship Item A: 2 B: 1
Relationship Item A: 1 B: 7
Relationship Item A: 7 B: 3
Relationship Item A: 3 B: 4
Relationship Item A: 4 B: 5
Relationship Item A: 5 B: 6

using a sort method that uses a comparer

As you can see B will equal A on the next line, with the first line being A that has no B reference, and the last line being B with no A reference. I have pasted the code below, I need to get the CompareTo working as such so the above list is sorted the way I want, any help is appreciated

The below code represents the collection in a simple console app which i have created, the list produced in my "real world app" produces the list in the same way I have replicated below in my console test app.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SortApplication
{
public class Relationship : IComparable<Relationship>
 {
public Relationship(int a, int b)
  {
  A = a;
  B = b;
  }

  public int A;
  public int B;

  int IComparable<Relationship>.CompareTo(Relationship other)
  {
  return (this.A.CompareTo(other.B));
  }

}

 
class Program
  {
 
List<Relationship> Relationships;
 
private void DoStuff()
  {
  Relationships = new List<Relationship>();

  Relationships.Add(new Relationship(3, 4));

  Relationships.Add(new Relationship(4, 5));

  Relationships.Add(new Relationship(7, 3));

  Relationships.Add(new Relationship(1, 7));

  Relationships.Add(new Relationship(5, 6));

  Relationships.Add(new Relationship(2, 1));


Console.WriteLine("BEFORE SORT\r\n");

foreach (var item in Relationships)

  {
Console.WriteLine("Relationship Item A: {0} B: {1}", item.A, item.B);

  }


Relationships.Sort(); 

 
Console.WriteLine("AFTER SORT\r\n");

foreach (var item in Relationships)

  {
Console.WriteLine("Relationship Item A: {0} B: {1}", item.A, item.B);

  }

  }

static void Main(string[] args)
  {

Program p = new Program();

  p.DoStuff();

Console.ReadKey();

  }
  }
}



Answers (4)