Sort Criteria for Generic.List ???

  • Thread starter Thread starter Peter Olcott
  • Start date Start date
P

Peter Olcott

How does not specify the sort criteria for Generic.List ??
The way that this is done in C++ STL is to implement operator<(), how is this
done in C# and DotNet for Generic.List ???
 
Hi Peter,

You can sort a generic list easily using an anonymous method.

Take the following class for example:

class MyObject
{
// public for the sake of example
public string stringField;

public MyObject(string stringField)
{
this.stringField = stringField;
}
}

You can create a generic list of MyObjects as follows:

List<MyObject> list = new List<MyObject>();

// note: add the objects unsorted on stringField:
list.Add(new MyObject("string 2"));
list.Add(new MyObject("string 3"));
list.Add(new MyObject("string 1"));

Sort them by their stringField value:

list.Sort(
// anonymous method
delegate(MyObject mo1, MyObject mo2)
{
// Perform any comparison that you'd like here.
// In this example, we're just comparing stringFields
return mo1.stringField.CompareTo(mo2.stringField);
});

Result:

Debug.Assert(list[0].stringField == "string 1", "index 0 invalid");
Debug.Assert(list[1].stringField == "string 2", "index 1 invalid");
Debug.Assert(list[2].stringField == "string 3", "index 2 invalid");
 

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

Similar Threads

binding a Generic.List to a repeater 5
Generic.List 2
Property. 3
Generic.List 1
Find in Generic.List 3
CheckBox 1
Generic.List 1
String 2

Back
Top