Sort List<string> like Excel columns sort

|▌冷眼眸甩不掉的悲伤 提交于 2020-01-10 05:20:23

问题


Please consider this List:

"A", "C", "AB", "AD", "N", "Z", "AC"

I want to sort this string (That are being Excel column) like Excel Column Sorting.

I want the result like this:

"A", "C", "N", "Z", "AB", "AC", "AD"

Is it possible using LINQ OrderBy?

What is the best approach?

Thanks


回答1:


Update: Thanks @JeppeStigNielsen for correct comment, I add StringComparer.Ordinal to support in all cultures:

var result = List.OrderBy(p=>p.Length).ThenBy(p=>p,StringComparer.Ordinal);



回答2:


First order by the length of column name ("C" comes before "AB"), then use normal alphabetical (string) sorting on strings with same length ("AC" before "AD").

var columns = new[] { "A", "C", "AB", "AD", "N", "Z", "AC" };
var sorted = columns.OrderBy(c => c.Length)
                    .ThenBy(c => c);


来源:https://stackoverflow.com/questions/34488997/sort-liststring-like-excel-columns-sort

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