C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,307 questions
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Hi,
How to use Sort function.
The run-time exception occurs when I use the function
private void Button_Clicked(object sender, EventArgs e)
{
List<AbcData> parts = new List<AbcData>();
parts.Add(new AbcData() { letter = "B", number = 5 });
parts.Add(new AbcData() { letter = "C", number = 4 });
parts.Add(new AbcData() { letter = "A", number = 2 });
parts.Add(new AbcData() { letter = "E", number = 1 });
parts.Add(new AbcData() { letter = "D", number = 3 });
parts.Sort(); // System.InvalidOperationException: 'Failed to compare two elements in the array
}
. . .
public class AbcData
{
public int number { get; set; }
public string letter { get; set; }
}
private void Button_Clicked(object sender, EventArgs e)
{
List<AbcData> parts = new List<AbcData>( );
parts.Add( new AbcData( ) { letter = "B", number = 5 } );
parts.Add( new AbcData( ) { letter = "C", number = 4 } );
parts.Add( new AbcData( ) { letter = "A", number = 2 } );
parts.Add( new AbcData( ) { letter = "E", number = 1 } );
parts.Add( new AbcData( ) { letter = "D", number = 3 } );
parts.Sort( );
}
public class AbcData : IComparable
{
//you need to implement explicitly member of IComparable
public int CompareTo( object o )
{
AbcData o2 = (AbcData)o;
return number.CompareTo( o2.number );
}
public int number
{
get; set;
}
public string letter
{
get; set;
}
}
See samples in MSDN : List<T>.Sort Method
or from Google : How to sort a list in C#
The run-time exception occurs when I use the function
And which exception exactly do you get or do we have to guess?
You use a customer class and that one must implement IComparable<T> Interface to be sortable.