我有一个列表,我想以与当前相反的顺序对结果进行排序,以模仿用户单击列标题超链接。目前,我有以下内容:
dsList.Sort((x, y) => String.CompareOrdinal(x.DisplayName, y.DisplayName));
但这仅按升序排序。我知道我会做降序排序:
dsList.Sort((x, y) => String.CompareOrdinal(x.DisplayName, y.DisplayName)*-1);
但是,我不想检测它当前是什么并决定执行哪种操作。
有道理吗?
谢谢。
澄清一下,我无法使用 Reverse,因为我有超过 1 列可以排序,因此我需要能够指定要排序的值。
下面的方法有效,但不适用于空值。如果有空白,排序就会卡住。
dsList.Sort((x, y) => String.CompareOrdinal(x.Surname, y.Surname) * (strB != null && (strA != null && String.Compare(strA, strB) == -1) ? -1 : 1));
最佳答案
怎么样
dsList.Sort((x, y) => String.CompareOrdinal(x.DisplayName, y.DisplayName)*(dsList[0] < dsList[1]?-1:1));
编辑:在您的评论中,当存在重复或空值时,您似乎遇到了问题......这应该可以解决这个问题
dsList.Sort((x, y) => String.CompareOrdinal(x.DisplayName, y.DisplayName)*String.CompareOrdinal(dsList[0].DisplayName, dsList[dsList.Length-1].DisplayName));
关于c# - 按 desc 或 asc 对列表进行排序,具体取决于当前列表的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14350238/