views:

2915

answers:

5

Exception: Failed to compare two elements in the array.

private void assignNames(DropDownList ddl, Hashtable names)
{
    List<ListItem> nameList = new List<ListItem>();
    if (ddl != null)
    {
        ddl.ClearSelection();
        ddl.Items.Add(new ListItem("Select Author"));
        foreach (string key in names.Keys)
        {
            nameList.Add(new ListItem(names[key].ToString(), key));

        }

    nameList.Sort();
}

So how can I use Sort() to compare on the "names" and not get stuck on the key?

+1  A: 

what type of object is "names"?

EDIT: From what I can tell you will have to specify an IComparer for this to work, not sure if I fully understand what you are trying to do though.

EDIT: This is way too complicated for what I "feel" your intent is, you basically want to populate a dropdown list with a sorted list of Author names.

you should be able to have a

List<string> auhtorNames;
authorNames.Sort();
ddl.DataSource = authorNames;
ddl.DataBind();
Marcus King
Names is a hashtable, sorry
scrot
I've fixed the code to show everything
scrot
A: 

Use ArrayList.Sort(IComparer) instead of ArrayList.Sort().

BQ
A: 

ListItem is not Comparable. you could use a System.Collections.Specialized.OrderedDictionary instead.

Jimmy
+10  A: 

Provide a Comparison<T> to instruct the List on how to sort the items.

nameList.Sort(delegate(ListItem thisItem, ListItem otherItem) {
    return thisItem.Text.CompareTo(otherItem.Text);
});

You might also want to check for null to be complete, unless you already know there won't be any, as in this case.

bdukes
You could also use a lambda expression instead of the anonymous delegate, if you'd prefer and can use .NET 3.5.
bdukes
Just curious, how would you do this in VB.NET?
thismat
nameList.Sort(Function(thisItem as ListItem, otherItem as ListItem) return ...)
bdukes
Worked, thank you
scrot
Much appreciated.
thismat
There's no `Return` in VB lambda syntax, though. It's just `Function(x, y) x.Text.CompareTo(y.Text)` - and you do not need types for arguments, as they're deduced.
Pavel Minaev
+1  A: 

nameList=nameList.OrderBy(li => li.Text).ToList();

Jacob Adams