How to put empty strings at the end when sorting

时光毁灭记忆、已成空白 提交于 2019-12-11 19:48:35

问题


When sorting a column on my WebGrid from A to Z, the empty strings always come up first, so I have :

""
""
"A"
"B"

(Without the quotes of course).

I want them to come up last, is there a simple way to do this ?


回答1:


you should sort with generic Comparison delegate like this one:

private int MyComparison(string x, string y)
    {
        if (string.IsNullOrEmpty(x))
        {
            if (string.IsNullOrEmpty(y))
            {
                // If x is null and y is null, they're 
                // equal.  
                return 0;
            }
            else
            {
                // If x is null and y is not null, y 
                // is greater.  
                return 1;
            }
        }
        else
        {
            // If x is not null... 
            // 
            if (string.IsNullOrEmpty(y))
            // ...and y is null, x is greater.
            {
                return -1;
            }
            //sort them with ordinary string comparison
            else
                return x.CompareTo(y);
        }
    }

List<string> liststring = new List<string>() {"C", "","A","","B"};
liststring.Sort(MyComparison);


来源:https://stackoverflow.com/questions/24303481/how-to-put-empty-strings-at-the-end-when-sorting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!