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]
CodePudding user response:
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;
}
CodePudding user response:
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));
CodePudding user response:
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;
}
CodePudding user response:
A simpler way is to sort g
and kg
separately and then combine them into one.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
public class Program
{
public static void Operation()
{
var array = new List<string> {"100g", "1.5kg", "250g"};
var sortByG = array
.Where(str => Regex.Match(str, @"\dg$").Success)
.OrderBy(str => str);
var sortByKg = array
.Where(str => Regex.Match(str, @"\dkg$").Success)
.OrderBy(str => str);
var result = sortByG.Concat(sortByKg);
Console.WriteLine(string.Join(", ", result));
}
}
In Regex, \d
means digital, and $
means last. Please see here for more details.