Andando dai commenti precedenti, vorrei anche implementare una classe personalizzata IComparer<T>
. Da quello che posso raccogliere, la struttura degli elementi è un numero, una combinazione di un numero seguito da una o più lettere. In questo caso, dovrebbe essere implementata la seguente implementazione IComparer<T>
.
public class CustomComparer : IComparer<string>
{
public int Compare(string x, string y)
{
var regex = new Regex("^(d+)");
// run the regex on both strings
var xRegexResult = regex.Match(x);
var yRegexResult = regex.Match(y);
// check if they are both numbers
if (xRegexResult.Success && yRegexResult.Success)
{
return int.Parse(xRegexResult.Groups[1].Value).CompareTo(int.Parse(yRegexResult.Groups[1].Value));
}
// otherwise return as string comparison
return x.CompareTo(y);
}
}
Con questo IComparer<T>
, sarete in grado di ordinare l'elenco dei string
facendo
var myComparer = new CustomComparer();
myListOfStrings.Sort(myComparer);
Questo è stato testato con i seguenti elementi:
2, 1, 4d, 4e, 4c, 4a, 4b, A1, 20, B2, A2, a3, 5, 6, 4f, 1a
e dà il risultato:
1, 1a, 2, 20, 4a, 4b, 4c, 4d, 4e, 4f, 5, 6, A1, A2, a3, B2
Rompere il 'numero' in componenti, quindi ordinare da questo. – leppie
sì, ordinamento naturale è ciò che ur dopo. questo è un duplicato come dichiarato da Jon. Un buon articolo su http://zootfroot.blogspot.com.au/2009/09/natural-sort-compare-with-linq-orderby.html –
[Natural Sorting in C#] (http: //www.interact -sw.co.uk/iangblog/2007/12/13/natural-sorting) –