Reputation: 1326
I have a list of strings of distances which goes like follows:
1.3 km
20 km
44 km
22.5 km
26.7 km
Currently I am ordering them by length and then "alphabetically" with:
listofdistances.OrderBy(x => x.Distance.Length).ThenBy(x => x.Distance)
This will give me a list ordered as follows:
20 km
44 km
1.3 km
22.5 km
26.7 km
That is what the code does and I understand it. Now i would like a solution to sort the strings by actual distances, but i dont know how to achieve it:
1.3 km
20 km
22.5 km
26.7 km
44 km
Any help is greatly appreciated.
Upvotes: 0
Views: 227
Reputation: 162
if there is a split of space always and unit is always same
var v = ls.Select(x => x.Split(' '));
var v2 = v.OrderBy(x=>Convert.ToDouble(x[0]));
var v3 = v2.Select(z=>z.Aggregate((x, y) => x.ToString() + " " + y));
Upvotes: 0
Reputation: 136
You can use it in Linq also
string[] h = new string[] { "1.3 km","20 km","44 km","22.5 km","26.7 km" };
h.Select(g => double.Parse(g.Trim().Split(' ')[0])).OrderBy(g => g).Select(x => x + " Km")>toList();
Upvotes: 0
Reputation: 13179
You can create a natural sort equality comparer.
public class DistanceNaturalSort : IComparer<string>
{
int IComparer<string>.Compare(string x, string y)
{
try
{
var valX = double.Parse(Regex.Match(x, @"\d+(\.\d+)?").Value);
var valY = double.Parse(Regex.Match(y, @"\d+(\.\d+)?").Value);
if (valX == valY)
return 0;
else if (valX < valY)
return -1;
else
return 1;
}
catch (Exception)
{
return ((new CaseInsensitiveComparer()).Compare(y, x));
}
}
}
Then, you just pass in your comparer to the first order by:
var comparer = new DistanceNaturalSort();
var sorted = listofdistances.OrderBy(x => x, comparer);
Upvotes: 4
Reputation: 924
Kindly refer the following, I think the one you are looking for.
&
The Java Comparator Implementation
.
Upvotes: -1