简体   繁体   中英

c# list strings with containing numbers orderby

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.

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);

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();

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));

Kindly refer the following, I think the one you are looking for.

The Alphanum Algorithm

&

The Java Comparator Implementation .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM