Reputation: 33
I have an array list of List<string>
that contains values in the following order [100g, 1.5kg, 250g]
now when I try to sort them I am not getting the expected result and it is sorting in the following order.
I am using array.OrderBy(x => x);
[1.5kg, 100g, 250g]
How can I sort them according to their weight?
the correct should be:
[100g, 250g, 1.5kg]
Upvotes: 1
Views: 277
Reputation: 3612
I think a better solution starts from the data you are storing.
I prefer to store all the data as decimals instead of strings, I will define a business rule to store the values in Grams.
Later on the front end, I will decide if I will display as g, kg, pounds, etc.
This approach will remove any sorting overhead. Later, the front end can decide on conversion, and your back end is decoupled.
Upvotes: 2
Reputation: 3495
You can normalize all array elements to g. Then sort as numbers and finally convert to g or kg.
sample code:
private string[] normalaizeArray(string[] inputArray)
{
for (int i= 0 ; i < inputArray.Length; i++)
{
if(inputArray[i].Contains('k'))
{
inputArray[i] = (float.Parse(inputArray[i].Split('k')[0]) * 1000).ToString();
}
else
{
inputArray[i] = inputArray[i].Replace("g", "");
}
}
inputArray = inputArray.OrderBy(x => int.Parse(x)).ToArray();
for (int i = 0; i < inputArray.Length; i++)
{
if(int.Parse(inputArray[i])>1000)
inputArray[i] = (float.Parse(inputArray[i])/1000).ToString() + "kg";
else
inputArray[i] = inputArray[i] + 'g';
}
return inputArray;
}
Upvotes: 2
Reputation: 2417
try parse to g and sort it
public void GOGO()
{
List<string> ay = new List<string>()
{
"1.5kg","100g","1600g"
};
IOrderedEnumerable<string> orderList = ay.OrderBy(x => WeightG(x));
foreach(string s in orderList)
{
Console.WriteLine(s);//here
}
}
public int WeightG(string weighStr)
{
if (weighStr.Contains("kg"))
{
string num = weighStr.Split('k')[0];
return (int)(float.Parse(num) * 1000);
}
if (weighStr.Contains("g"))
{
string num = weighStr.Split('g')[0];
return int.Parse(num);
}
return 0;
}
Upvotes: 3
Reputation: 2072
I have a simpler and elegant solution with less code:
string[] a = new string[] { "7.2kg", "1.5kg", "100g", "250g" };
var lstKg = a.ToList().Where(x => x.Contains("kg")).Select(y => double.Parse(y.Replace("kg", String.Empty))).OrderBy(k=>k).Select(o=>o+"kg").ToList();
var lstG = a.ToList().Where(x => !lstKg.Contains(x)).Select(y => double.Parse(y.Replace("g", String.Empty))).OrderBy(k=>k).Select(o =>o+"g").ToList();
lstG.AddRange(lstKg);
lstG.ForEach(item => Console.WriteLine(item));
Upvotes: 2