【发布时间】:2021-02-12 03:38:36
【问题描述】:
我正在尝试根据列表中每个项目的价格对列表进行排序。
这是我希望输出的样子:
ROLLS_ROYCE1 -- 6.608 €
ROLLS_ROYCE3 -- 4.956 €
ROLLS_ROYCE2 -- 0.826 €
但是,这是当前输出的实际情况:
ROLLS_ROYCE1 -- 6.608 €
ROLLS_ROYCE2 -- 0.82 €
ROLLS_ROYCE3 -- 4.956 €
这是我的代码:
public void MyFunction()
{
List<string> mylist = new List<string>(new string[]
{
"ROLLS_ROYCE1 -- 0,826 € -- 8 PCS -- 14:02:53.876",
"ROLLS_ROYCE2 -- 0,826 € -- 1 PCS -- 17:02:53.888",
"ROLLS_ROYCE3 -- 0,826 € -- 6 PCS -- 18:09:55.888"
});
foreach (string f in mylist)
{
decimal b = Convert.ToDecimal(GetPrice(f), CultureInfo.GetCultureInfo("de-DE")) * Convert.ToDecimal(GetPieces(f));
tradesforbigbuyslist += GetName(f) + " -- " + b.ToString() + " €" +
Environment.NewLine;
}
string[] splittedt2 = tradesforbigbuyslist.Split(new string[] {
System.Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
listBox3.DataSource = splittedt2;
}
public string GetPrice (string sourceline)
{
string newstring = sourceline;
string test1 = newstring.Replace(FetchThemAll.SubstringExtensions.Before(newstring, "--"), "");
string textIWant = test1.Replace("--", "");
string finalPrice = FetchThemAll.SubstringExtensions.Before(textIWant, "€");
return finalPrice;
}
public string GetPieces(string sourceline)
{
string ertzu = sourceline;
string ertzu1 = FetchThemAll.SubstringExtensions.Between(ertzu, "€", "PCS");
string ertzu2 = ertzu1.Replace("--", "");
return ertzu2;
}
public string GetName(string sourceline)
{
string barno = FetchThemAll.SubstringExtensions.Before(sourceline, "--");
return barno;
}
如何正确排序这些字符串?
【问题讨论】:
-
我稍微清理了代码的格式。看起来您缺少代码的开头(
listBox3.DataSource = splittedt2;之后的行上有一个不匹配的右括号},暗示它是方法的结尾,但方法的开头不在您原来的题)。所以,我把它放在一个名为MyFunction的函数中 - 但请随时将其更改为您的实际方法名称。 -
谢谢很多朋友@Donut
-
为什么不尝试创建一个将这些值存储为属性并将每一行表示为对象的类。然后一个简单的 linq 查询就可以做到这一点并生成输出。
-
为了帮助您修复代码,我们可能需要查看
SubstringExtensions——即minimal reproducible example。但是,您不能只使用" -- "子字符串使用string.Split(String, StringSplitOptions)拆分"ROLLS_ROYCE1 -- 0,826 € -- 8 PCS -- 14:02:53.876"字符串吗?请参阅:Split a string by another string in C#。您还可以使用相同的方法拆分0,826 €和8 PCS子字符串。 -
我通过 OrderByDescending 进行了尝试,但没有奏效 -- 那你能不能 edit 分享你的代码 minimal reproducible example -- 特别是没有成功的代码工作吗?
标签: c# arrays regex list sorting