【发布时间】:2021-09-30 16:51:57
【问题描述】:
我有一个如下所示的列表:
Apple - 67 $ - 345 PIECES - 19:03
Banana - 45 $ - 341 PIECES - 12:02
Monkey - 34 $ - 634 PIECES - 16:01
我想按(金额*金额)的排序结果排序该列表,类似于“最高订单排名”
finalResultOfTradeFiltering = finalResultOfTradeFiltering.OrderBy(x => Convert.ToDecimal(FindTextBetween(x,"-","$").Replace(" ", String.Empty)) * Convert.ToInt32(FindTextBetween(x, "-", "PIECES").Replace(" ", String.Empty))).ToList();
public string FindTextBetween(string text, string left, string right)
{
// TODO: Validate input arguments
int beginIndex = text.IndexOf(left); // find occurence of left delimiter
if (beginIndex == -1)
return string.Empty; // or throw exception?
beginIndex += left.Length;
int endIndex = text.IndexOf(right, beginIndex); // find occurence of right delimiter
if (endIndex == -1)
return string.Empty; // or throw exception?
return text.Substring(beginIndex, endIndex - beginIndex).Trim();
}
但是我的代码不断崩溃,说明格式不正确
有什么线索吗?
【问题讨论】:
-
它将基于
FindTextBetween代码,但我的猜测是FindTextBetween(x, "-", "PIECES")从第一个-中找到文本,因此您尝试格式化67$-345而不是@ 987654328@。请附上FindTextBetween代码,以便我们确认是否是问题所在。 -
你应该写一个类,可以使用类类型将字符串列表转换为列表。
-
我很确定我已经在 foreach 循环中测试了 FindTextBetween,它正确地输出了金额和件数,所以没有错
-
如果可能尝试使用
Regex,而不是查找索引并提取子字符串 -
是的,问题正如我所怀疑的那样。
FindTextBetween从-的第一次出现开始。因此,您要么需要更新它以传入它应该开始的索引,要么告诉它跳过第一次出现。或者更好的是编写一个方法来将整个字符串解析为一个带有值的类,然后在你的代码中使用它。
标签: c# arrays string list linq