我有一个文件,该文件具有一个产品ID(只能为8个字符),后跟一个新行,并且相对于新行的时间,其价格按升序排列。我需要打印ProductID和最新价格。
以下是文件内容的示例:
A1234567
200.000
300.000
B1234567
200.000
400.000
C12345678
100.00
200.00
因此在此示例中,我需要打印:
A1234567: 300.00
B1234567: 400.00
我使用了正则表达式来打印产品ID。但是我不知道如何获得最新价格。我当时想在产品ID之前加行,但是不确定如何做到这一点。
这是我的代码:
private static void OutputCusipPrice(string filePath)
{
using (StreamReader sr = File.OpenText(filePath))
{
String s = "";
Regex r = new Regex("^[a-zA-Z0-9]*$");
int pos = 0;
while ((s = sr.ReadLine()) != null)
{
if (r.IsMatch(s) && s.Length == 8)
{
Console.WriteLine(s);
}
else
{
double result;
if (Double.TryParse(s, out result))
{
Console.WriteLine(s);
}
}
}
}
}
答案 0 :(得分:1)
请尝试一下,这只是@Jason Boyd提到的实现
private static void OutputCusipPrice(string filePath)
{
using (StreamReader sr = File.OpenText(filePath))
{
String row = "", current="",previous = "", price = "";
bool skipInvalid = false; // This is to remove the negative case
Regex r = new Regex("^[a-zA-Z0-9]*$");
int pos = 0;
while ((row = sr.ReadLine()) != null)
{
if (r.IsMatch(row) && row.Length == 8)
{
current = row;
if (previous == "") previous = current;
if (current != previous )
{
previous = row;
Console.WriteLine("Price : " + price);
}
skipInvalid = false;
Console.WriteLine(row);
}
else
{
if (skipInvalid) continue;
double result;
if (Double.TryParse(row, out result))
{
price = result.ToString(); // cache the previous
}
else
{
skipInvalid = true;
}
}
}
if (previous != "")
{
Console.WriteLine("Price : " + price);
}
}
}
答案 1 :(得分:0)
这应该给您想要的结果。
var input = @"A1234567
200.000
300.000
B1234567
200.000
400.000
C1234567
100.00
200.00";
var productIds = Regex.Matches(input, @".{8}\r\n")
.Cast<Match>()
.Select((m, i) => new { index = i, value = m.Value });
var prices = Regex.Split(input, @".{8}\r\n").Where(r => !string.IsNullOrWhiteSpace(r))
.Select((r, i) => new { index = i, value = r });
var result = productIds.Join(prices, pro => pro.index, pri => pri.index, (pro, pri) => new {productid = pro.value,prices=Regex.Split(pri.value,@"\r\n")
.Where(r => !string.IsNullOrWhiteSpace(r))
.Reverse().ToArray()[0]});