12,506,733 members (54,361 online)
Tip/Trick
alternative version

7.4K views
2 bookmarked
Posted

# Numeric before alpha sort in LINQ

, 11 Feb 2013 CPOL
 Rate this:
Shows how to sort strings in LINQ ordering numbers as first word in order

## Introduction

This will help sort a list of strings that has the numbers as the first word in numeric order.

## Using the code

This is a code example, output and full compare class that shows how to use the string compare.

```// Example
IList<string> cMovies = new List<string>();

foreach (string cTitle in cMovies.OrderBy(t => t)) {
Console.WriteLine(cTitle);
}
Console.WriteLine("-----");
foreach (string cTitle in cMovies.OrderBy(t => t, new NumeralAlphaCompare())) {
Console.WriteLine(cTitle);
}
```
```// Output
007 Casino Royale
10.000 BC
1408
2 Fast 2 Furious
2012
21 jump Street
3:10 To Yuma
40 Days And 40 Nights
8 mm
-----
2 Fast 2 Furious
3:10 To Yuma
007 Casino Royale
8 mm
21 jump Street
40 Days And 40 Nights
1408
2012
10.000 BC ```
```// Compare class
using System.Collections.Generic;

public class NumeralAlphaCompare : IComparer<string> {
public int Compare(string x, string y) {
int nIndexX = x.Replace(":", " ").IndexOf(" ");
int nIndexY = y.Replace(":", " ").IndexOf(" ");
bool bSpaceX = nIndexX > -1;
bool bSpaceY = nIndexY > -1;

long nX;
long nY;
if (bSpaceX && bSpaceY) {
if (long.TryParse(x.Substring(0, nIndexX).Replace(".", ""), out nX)
&& long.TryParse(y.Substring(0, nIndexY).Replace(".", ""), out nY)) {
if (nX < nY) {
return -1;
}
else if (nX > nY) {
return 1;
}
}
}
else if (bSpaceX) {
if (long.TryParse(x.Substring(0, nIndexX).Replace(".", ""), out nX)
&& long.TryParse(y, out nY)) {
if (nX < nY) {
return -1;
}
else if (nX > nY) {
return 1;
}
}
}
else if (bSpaceY) {
if (long.TryParse(x, out nX)
&& long.TryParse(y.Substring(0, nIndexY).Replace(".", ""), out nY)) {
if (nX < nY) {
return -1;
}
else if (nX > nY) {
return 1;
}
}
}
else {
if (long.TryParse(x, out nX)
&& long.TryParse(y, out nY)) {
if (nX < nY) {
return -1;
}
else if (nX > nY) {
return 1;
}
}
}
return x.CompareTo(y);
}
}
```
I know there isn't much text to explain what is happening. But the code is really a bunch of `if` and `else` that compares two strings to see which has a number as first word and returns the compare result.

## Points of Interest

I hope you can use this little example to order strings as you wanted it to be sorted like windows sorts files in explorers.

## History

No history since this is the first version.

## Share

 Software Developer Denmark
No Biography provided

## You may also be interested in...

 Pro Pro

 First Prev Next
 My vote of 5 Kristian Koch11-Feb-13 10:33 Kristian Koch 11-Feb-13 10:33
 Last Visit: 31-Dec-99 18:00     Last Update: 27-Sep-16 20:18 Refresh 1