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

The file contains the following data

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

Each line has 1 entry which represents a room in a building.

How do I sort it numerically and alphabetically. So my results look like

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

The alphabetical part comes after the numbers.

software is fun
  • 7,286
  • 18
  • 71
  • 129

3 Answers3

4

You could use int.TryParse and an anonymous type + 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) returns a bool where true is "higher" than false. That's why all text-lines come last.

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
0

You'll want to implement your own IComparer. You can use this method to easily create it, using built in functions. If you must write it yourself, Tim's answer will give you what you want.

Community
  • 1
  • 1
Kyle W
  • 3,702
  • 20
  • 32
0

Take a look at Natural Comparing.

IComparer for natural sorting

http://www.codeproject.com/Articles/22517/Natural-Sort-Comparer

Community
  • 1
  • 1
Fabian Bigler
  • 10,403
  • 6
  • 47
  • 70