List sorting that prioritizes a specific value

I would like to sort this list of strings, giving priority to a specific row. In addition, the usual sorting of strings will be wonderful.

In this example, “why am I so dumb?”, Which is the most obvious thing we can solve from this question, is for sorting 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 line that should be at the top is somewhere in the middle of the list.

+2
source share
2 answers

. , s1 == "why am I so dumb?", , s2 == "why am I so dumb?" "why am I so dumb?". ( return ):

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);
}
+1

:-) :

stringList.Sort((s, s1) = > s == " ?" ? -1: s.CompareTo(s1));

stringList.Sort((s, s1) = > s == " ?" ? -1: (s1 == " ?" ? 1: s.CompareTo(s1) ));

+1

Source: https://habr.com/ru/post/1569878/


All Articles