HELP can't get arraylist to sort by alphabet

  • Thread starter Thread starter steve smith
  • Start date Start date
S

steve smith

Hi I am new to this language, and still don't understand most of the
concepts, I am trying to sort an arraylist by alphabet, I belive i
need to use the IComparer interface, but have no idea how this works?
Does anyone have a sample of how i can sort my arraylist of words.
Also how is an arraylist iterated over and is it possible to obtain a
count of the number of occurences of each owrd in the array list? Many
thanks.
 
Just call the Sort() method of your ArrayList. It will use the IComparable
implementation of the items in the list, in this case, strings. These
should sort as you expect; you don't have to do Sort(IComparer) unless have
some special requirements.

--Bob
 
Steve,

Missed the 2nd parts of your question.

You can iterate over an ArrayList of strings "al" in the following ways:

// for loop

for (int i = 0;i < al.Length;i++) {
string s = (string)al;
// do stuff with s
}

// foreach loop

foreach (string s in al) {
// do stuff with s
}

// IEnumerator interface

IEnumerator alEnumerator = al.GetEnumerator();

while (alEnumerator.MoveNext()) {
string s = (string)alEnumerator.Current;
// do stuff with s
}

To obtain a count of occurences you'll have to write your own routine, along
the lines of:

int Occurs(string strSearch,ArrayList al) {
int intCount = 0;

foreach (string s in al) {

if (s == strSearch) {
intCount++;
}

}

return intCount;
}

--Bob
 
Hi Steve,

To use the IComparer interface, use a class that implements IComparer, or create a dummy class that has no function besides sorting.

public class SortClass : IComparer
{
public int Compare(object x, object y)
{
// if x and y aren't strings
// they are considered equal
if(!(x is string) && !(y is string))
return 0;

// if x isn't a string (but y is)
// x is of lower value (earlier on the list)
if(!(x is string))
return -1;

// if y isn't a string (but x is)
// x is of higher value (lower on the list)
if(!(y is string))
return 1;

return String.Compare((string)x, (string)y);
}
}

The sorting algorithm is described in Compare(), which returns -1, 0 or 1 depending on if x is lower, equal or higher value than y. In my case, for simplicity I just used String.Compare and just return that value, which is the same as using ArrayList.Sort() without the IComparer. It will also place all non-strings at the top of the list, but does not attempt to sort the non-strings.

SortClass sc = new SortClass();
list.Sort(sc);
 
Back
Top