I have list of alphanumeric, I want this order first number and then character in descending order.
EH40, DH40, DH36,AH40, AH36,EH27S, DH32,EH32, AH32, DH27S, EH36
Expected result:
EH40, DH40, AH40, EH36, DH36, AH36 ,EH32, DH32 and so on
I have list of alphanumeric, I want this order first number and then character in descending order.
EH40, DH40, DH36,AH40, AH36,EH27S, DH32,EH32, AH32, DH27S, EH36
Expected result:
EH40, DH40, AH40, EH36, DH36, AH36 ,EH32, DH32 and so on
Try following :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace ConsoleApplication11
{
class Program
{
const string FILENAME = @"c:\temp\test.xml";
static void Main(string[] args)
{
string[] input = {"EH40", "DH40", "DH36","AH40", "AH36","EH27S", "DH32","EH32", "AH32", "DH27S", "EH36"};
string[] results = input.Select(x => new AlphaNumeric(x)).OrderBy(x => x).Select(x => x.input).ToArray();
}
}
public class AlphaNumeric : IComparable<AlphaNumeric>
{
string prefix { get; set; }
int number { get; set; }
public string input { get; set; }
static string pattern = @"(?'prefix'.*)(?'number'\d+)[^\d]*$";
public AlphaNumeric(string input)
{
this.input = input;
Match match = Regex.Match(input, pattern, RegexOptions.RightToLeft);
string numberStr = match.Groups["number"].Value;
number = int.Parse(numberStr);
prefix = match.Groups["prefix"].Value;
}
public int CompareTo(AlphaNumeric other)
{
int results = 0;
if (this.number != other.number)
{
results = this.number.CompareTo(other.number);
}
else
{
if (this.prefix == other.prefix)
{
results = this.input.CompareTo(other.input);
}
else
{
results = this.prefix.CompareTo(other.prefix);
}
}
return results;
}
}
}