Sorting a list of objects.... need property to be sorted alphabetically EXCEPT need items with a specific letter FIRST in list

StackOverflow https://stackoverflow.com/questions/23547015

  •  18-07-2023
  •  | 
  •  

Question

I have a Windows app that offers the user a drop-down list of strings. The data comes to us from a webservice that feeds us XML.

We loop through the XML nodes and create multiple objects:

Environment env = new Environment(id, name, type);

Each of those gets added to a list: listEnvs.Add(env);

Now, I'd like to sort that list by the "name" field, alphabetically, with a trick: anything starting with the letter "p" needs to come first (and should be alphabetized by the remaining letters, of course).

I can't use LINQ, as we're dealing with an app written coded for .NET 2.0 here and I don't have permission to change that (yet).

I just wanted to make it a bit easier on users, because 90% of the time, they'll want to select names from that drop-down that start with the letter "p". No sense forcing them to scroll through that dropdown list to get from the "A's" to the "P's" all the time.

Any thoughts on how I can pull off such a sort?

Thank you!

Was it helpful?

Solution

and apologies if this is overly simplistic or missing the point...

Have you tried using list.sort(compareFn) ?

eg:

private static int CompareEnv(Environment a, Environment b)
    {
        if (String.IsNullOrEmpty(a.name))
        {
            if (String.IsNullOrEmpty(b.name)) return 0;
            else return -1;
        }

        if (String.IsNullOrEmpty(b.name)) return 1;

        if (a.name.StartsWith("P"))
        {
            if (b.name.StartsWith("P")) return a.name.CompareTo(b.name);
            else return -1;
        }

        if (b.name.StartsWith("P")) return 1;

        return a.name.CompareTo(b.name);
    }

{

// your code for setting up the list

    listEnvs.Sort(CompareEnv);

}

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top