user4624979
user4624979

Reputation:

How to have a "sorted" ListBox with the first item out of order?

Is there an easy way to have a Sorted ListBox that automatically places a particular item "first" (out of the usual order)? For example, if I have a dynamic list of Country names, but I want a particular country first. Do I simply override the Sort() method to accomplish that?

One way would be to enable the Sorted Property, then disable it, then the Sort() Method could pick out the desired value and move it to the first position in the Items collection (for example, using Insert() ). Is this the best way (or only way) to do this?

I used to do this with the Contacts in my phone by embedding a space (or two) at the start of the item(s) I wanted first in my list. Would that also work?

Upvotes: 1

Views: 913

Answers (2)

Kip Morgan
Kip Morgan

Reputation: 738

You can do it by implementing your own comparer and passing into the Sort method:

class Employee
{
    public string Name { get; set; }
    public int Salary { get; set; }
}

class Sorter : IComparer<Employee>
{
    public int Compare(Employee x, Employee y)
    {
        string nameAtTop = "Lucy";

        string xName = x.Name;

        if (x.Name.Equals(nameAtTop))
        {
            xName = "_";
        }

        string yName = y.Name;

        if (y.Name.Equals(nameAtTop))
        {
            yName = "_";
        }

        return (xName.CompareTo(yName));
    }
}

static void Main(string[] args)
{
    List<Employee> list = new List<Employee>();
    list.Add(new Employee() { Name = "Steve", Salary = 10000 });
    list.Add(new Employee() { Name = "Janet", Salary = 10000 });
    list.Add(new Employee() { Name = "Andrew", Salary = 10000 });
    list.Add(new Employee() { Name = "Bill", Salary = 500000 });
    list.Add(new Employee() { Name = "Lucy", Salary = 8000 });

    Sorter sorter = new Sorter();
    list.Sort(sorter);

    foreach (var element in list)
    {
        Console.WriteLine(element.Name);
    }
}

Upvotes: 0

Gaspa79
Gaspa79

Reputation: 5615

If you are only going to add items to that list once, I'd suggest to make a list with all the non-special values, sort it, and then add the special values at index 0 with List.Insert(0, yourSpecialObj).

You can then put those items on the listbox.

Upvotes: 1

Related Questions