Sort Method for Collection

Y

Yehia A.Salam

Hello,

I have a collection of nodes and I want to sort then by certain property, I
create a Node class which implements the IComparable interface:
public class Node : IComparable{ ...
public int CompareTo(object obj) {
Node NodeB = (Node)obj;
return fW.CompareTo(NodeB.fW);
}

I have a NodeList derived from Collection:
public class NodeList : Collection<Node>;

But I'm not sure how to write the sort method in the NodeList??

Thanks In Advance
Yehia A.Salam
 
M

Marc Gravell

Actually, I suspect that if you change IComparable to
IComparable<Node>, and use a List<Node> (rather than
Collection<Node>), then you can just call list.Sort();

public class Node : IComparable<Node>
{
// ...
public int CompareTo(Node obj)
{
return fw.CompareTo(obj.fw);
}
}

Marc
 
I

Ignacio Machin ( .NET/ C# MVP )

Hello,

I have a collection of nodes and I want to sort then by certain property, I
create a Node class which implements the IComparable interface:
public class Node : IComparable{ ...
     public int CompareTo(object obj) {
                Node NodeB = (Node)obj;
                return fW.CompareTo(NodeB.fW);
     }

I have a NodeList derived from Collection:
public class NodeList : Collection<Node>;

But I'm not sure how to write the sort method in the NodeList??

Thanks In Advance
Yehia A.Salam

You do not need to implement IComparable nor derive from Collection,
in fact you do not need to create a colelction at all

using a List<Node> would be something like myList.Sort( delegate(Node
n1, Node n2){ if n1.prop==n2.prop) return 0;
if ( n1.prop< n2.prop) return -1;
return 1;} );
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top