问题
I have numbers that are getting converted to string. for example I have an amount 20000 and I have to show it as 200.00 so I am performing
string Amount = $"{Convert.ToDouble(x.Amount) / 100:0.00}"
and then I store them to list of amounts with values
200.00, 30.00, 588888.00, 56.36,
I tried sorting it by orderby(x=>x.Anount)
but this sorts on basis of string with first number as
200.00, 30.00, 56.36, 58888.00
I want the output to be sorted as
30.00, 56.36, 200.00, 588888.00
回答1:
Pass a custom comparer into OrderBy. Enumerable.OrderBy will let you specify any comparer you like.
void Main()
{
string[] decimals = new string[] { "30.00", "56.36", "200.00", "588888.00" };
foreach (var dec in decimals.OrderBy(x => x, new DecimalComparer()))
{
Console.WriteLine(thing);
}
}
public class DecimalComparer: IComparer<string>
{
public int Compare(string s1, string s2)
{
if (IsDecimal(s1) && IsDecimal(s2))
{
if (Convert.ToDecimal(s1) > Convert.ToDecimal(s2)) return 1;
if (Convert.ToDecimal(s1) < Convert.ToDecimal(s2)) return -1;
if (Convert.ToDecimal(s1) == Convert.ToDecimal(s2)) return 0;
}
if (IsDecimal(s1) && !IsDecimal(s2))
return -1;
if (!IsDecimal(s1) && IsDecimal(s2))
return 1;
return string.Compare(s1, s2, true);
}
public static bool IsDecimal(object value)
{
try {
int i = Convert.ToDecimal(value.ToString());
return true;
}
catch (FormatException) {
return false;
}
}
}
回答2:
try
orderby(x=>double.Parse(x.Amount))
回答3:
This should work
var numberstring = "100.0,300.00,200.00,400.00";
var array = numberstring.Split(',');
var sortedstring = array.OrderBy(x => double.Parse(x)).Aggregate("", (current, val) => current + (val + ","));
回答4:
You can sort by the Length property which will provide the desired order. For example:
IEnumerable<string> sizes = new List<string> { "200.00", "30.00", "56.36", "58888.00" };
sizes = sizes.OrderBy(x => x.Length);
回答5:
You can do it in one line:
var orderedAsString =
amounts.Select(x => double.Parse(x.Amount) / 100)
.OrderBy(x => x)
.Select(x => x.ToString("0.00"));
来源:https://stackoverflow.com/questions/36746496/sort-numbers-with-decimals-that-are-stored-in-string