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
}


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(oDataIdea));
}
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.

Read the complete post at http://alexrazon.blogspot.com/2006/11/arraylist-sorting-via-icomparable_27.html

Published 11-27-2006 7:13 AM by Alexis' Blog
Filed under: ,