列表排序优先特定值 [英] List sorting prioritizing particular value

查看:120
本文介绍了列表排序优先特定值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想排序字符串某些字符串优先名单。除此之外,普通字符串排序将被罚款。

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.

推荐答案

您比较例程是不完整的。您已经占到情况下 S1 ==为什么我这么愚蠢?,而不是其中 S2 ==为什么我的情况下,如此愚蠢?或者两个的是为什么我这么愚蠢?。添加这些情况下,应该可以解决这个问题(再加上你可以通过收益从案件ING简化它):

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

这篇关于列表排序优先特定值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆