正确排序String数组的方法

时间:2014-04-07 15:32:51

标签: c# arrays sorting

System.Collections.Generic.IEnumerable<String> lines = File.ReadLines("K:\\file.txt");

该文件包含以下数据

1
2
3
99
32
HR210
Redmond City Room A
23
Telephone Conference
HR252

每行有1个条目,代表建筑物中的一个房间。

如何以数字和字母顺序对其进行排序。所以我的结果看起来像

1
2
3
23
32
99
HR210
HR252
Redmond City Room A
Telephone Conference

字母部分出现在数字之后。

3 个答案:

答案 0 :(得分:4)

您可以使用int.TryParse和匿名类型+ Enumerable.OrderBy

int i;
lines = lines
    .Select(l => new { Line = l, IsText = !int.TryParse(l, out i), Value = i })
    .OrderBy(x => x.IsText)
    .ThenBy(x => x.Value).ThenBy(x => x.Line)
    .Select(x => x.Line);

.OrderBy(x => x.IsText)会返回bool,其中true是&#34;更高&#34;比false。这就是为什么所有文本行都持续的原因。

答案 1 :(得分:0)

您需要实现自己的IComparer。您可以使用this method使用内置函数轻松创建它。如果你必须自己写,Tim的回答会给你你想要的东西。

答案 2 :(得分:0)