Monday, November 27, 2006

ArrayList sorting via IComparable

The problem: I have a two-dimensional object array. Each first level element of the array contains five object elements--except for the last one, which only has three. However, I have a procedure that needs to concatenate another array at the end of the original one. Since I need to put the unique three-element object array at the end of the list, I had to find a solution to sort it via the elements' length.

The immediate solution was to use ArrayList.Sort(IComparer). Okay I created a class that looked similar to this:

class MyComparer : IComparable
{
private object _data;
public object Data
{
get { return _data; }
}
public MyComparer(object data)
{
_data = data;
}

int IComparable.CompareTo(object obj)
{
MyComparer mc = (MyComparer)obj;
object[] myData = this._data as object[];
object[] thatData = mc.Data as object[];
return (myData.Length < thatData.Length) ? 0 : -1; }
}


To use it in one of my methods:

private static object[] _sortChartData(object[] oData)
{
ArrayList arrData = new ArrayList();
for (int i = 0; i < oData.Length; i++) {
arrData.Add(new MyComparer(oData[i]));
}
arrData.Sort();
for (int j = 0; j < arrData.Count; j++) {
arrData[j] = (arrData[j] as MyComparer).Data;
}
return arrData.ToArray();
}


With this I can sort the contents of the original object[] to the one desired.

Labels: ,

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home