IAmJaeger
IAmJaeger

Reputation: 41

List sorting prioritizing particular value

I'd like to sort this list of strings giving priority to a certain string. Beyond that, the ordinary string sorting will be fine.

In this example, "why am I so dumb?", which is the most obvious thing we can get out of this question, is intended to be sorted at the top of the list.

static void Main(string[] args)
{
    List<string> stringList = new List<string>() 
    { "foo", "bar", "why am I so dumb?", "tgif" };

    stringList.Sort(StringListSorter);

    stringList.ForEach(x => Console.Out.WriteLine(x));
}

static int StringListSorter(string s1, string s2)
{
    int retVal = 0;

    if (s1 == "why am I so dumb?")
    {
        retVal = -1;
    }
    else
    {
        retVal = s1.CompareTo(s2);
    }

    return retVal;
}

In this example, the string desired to be at the top is somewhere in the middle of the list.

Upvotes: 3

Views: 551

Answers (2)

D Stanley
D Stanley

Reputation: 152634

Your comparison routine is incomplete. You have accounted for the case where s1 == "why am I so dumb?", but not the cases where s2 == "why am I so dumb?" or where both are "why am I so dumb?". Adding those cases should fix the problem (plus you can simplify it by returning from the cases):

static int StringListSorter(string s1, string s2)
{
    if (s1 == s2)
        return 0;
    if (s1 == "why am I so dumb?")
        return -1;
    if (s2 == "why am I so dumb?")
        return 1;
    return s1.CompareTo(s2);
}

Upvotes: 1

Quazer
Quazer

Reputation: 383

I don't undestand the question :-) But, may be:

stringList.Sort((s, s1) => s == "why am I so dumb?" ? -1 : s.CompareTo(s1));

or

stringList.Sort((s, s1) => s == "why am I so dumb?" ? -1 : (s1 == "why am I so dumb?" ? 1 : s.CompareTo(s1)));

Upvotes: 1

Related Questions