Monday, January 10, 2011

Sort Classes C#

I had a problem in C# where I needed to sort an array of classes based on one of the properties. It posed several issues, firstly the class definition came from a web service I wasn't in control of I couldn't implement IComparable which would have allowed me to use the sort routine. I suppose I could have made my own structure that implemented IComparable but given this was a quick fix I used a simple bubble sort. Not very efficient but simple and robust and given the datasets are usually less then 10 elements (and never more than 26) should be efficient enough. NB this is a cut down version that runs as a console application.


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

namespace BubbleSort_2
{
class Program
{
///
/// Simple Structure to represent insight
///

public class insight
{
public Name_match_indicator nameMatchIndicator { get; set; }
}
///
/// Name Match Indicator, this is from the Equifax Project
///

public enum Name_match_indicator
{
A = 0,
B = 1,
C = 2,
D = 3,
E = 4,
F = 5,
G = 6,
H = 7,
I = 8,
J = 9,
K = 10,
L = 11,
M = 12,
N = 13,
P = 14,
Q = 15,
R = 16,
S = 17,
T = 18,
U = 19,
V = 20,
W = 21,
X = 22,
Y = 23,
Z = 24,
}

static void Main(string[] args)
{
Random random = new Random();
string tmp;
// array to hold values
insight[] a = new insight[10];
for (int i1 = 0; i1 < a.Length; i1++) { //Generate a random character tmp = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65))).ToString(); a[i1] = new insight(); //convert random char into Enumerated type a[i1].nameMatchIndicator = (Name_match_indicator)Enum.Parse(typeof(Name_match_indicator), tmp); } // number of elements in array int x = a.Length; int i; int j; insight temp = new insight(); for (i = (x - 1); i >= 0; i--)
{
for (j = 1; j <= i; j++) { //Make the Comparison if (a[j - 1].nameMatchIndicator.CompareTo(a[j].nameMatchIndicator) > 0)
{
// if they arnt comparable switch them.
temp = a[j - 1];
a[j - 1] = a[j];
a[j] = temp;
}
}
}

for (int k = 0; k < x; k++) { Console.WriteLine("{0}. {1}", k, a[k].nameMatchIndicator); } Console.Read(); } } }
Post a Comment