【发布时间】:2016-01-11 16:01:20
【问题描述】:
我正在尝试解析这个具有超过 8,000 行硬编码数据验证的单一方法。对于数据源中的不同字段,其中大部分是相同的、重复的逻辑。
很多看起来像这样(C++):
temp_str = _enrollment->Fields->FieldByName("ID")->AsString.SubString(1,2);
if (temp_str.IsEmpty())
{ /* do stuff */ }
else
{
if (!IsDigitsOnly(temp_str))
{ /* do different stuff */ }
else
{ /* do other stuff */ }
}
temp_str = _enrollment->Fields->FieldByName("OtherField");
if (temp_str.IsEmpty())
/* do more stuff */
所以基本上,我只需要解析出每对 temp_str = ... 之间的值,然后获取每个唯一的验证“块”。
我目前遇到的问题是确定每个“块”的开始和结束位置。
这是我的代码:
static void Main(string[] args)
{
string file = @"C:\somePathToFile.h";
string validationHeader = "temp_str = _enrollment->Fields->FieldByName(";
string outputHeader = "=====================================================";
int startOfNextValidation;
List<string> lines = File.ReadAllLines(file).ToList<string>();
List<string> validations = new List<string>();
while (lines.Contains(validationHeader))
{
//lines[0] should be the "beginning" temp_str assignment of the validation
//lines[startOfNextValidation] should be the next temp_str assignment
startOfNextValidation = lines.IndexOf(validationHeader, lines.IndexOf(validationHeader) + 1);
//add the lines within that range to another collection
// to be iterated over and written to a textfile later
validations.Add((lines[0] + lines[startOfNextValidation]).ToString());
//remove everything up to startOfNextValidation so we can eventually exit
lines.RemoveRange(0, startOfNextValidation);
}
StreamWriter sw = File.CreateText(@"C:\someOtherPathToFile.txt");
foreach (var v in validations.Distinct())
{
sw.WriteLine(v);
sw.WriteLine(outputHeader);
}
sw.Close();
}
我的while 语句永远不会被命中,它只是立即跳转到StreamWriter 创建,因为validations 是空的,所以它会创建一个空文本文件。
所以我想我的第一个问题是,你如何循环 List 同时检查以确保这些项目中仍有包含特定“子值”的项目?
编辑:
我也试过了;
while (lines.Where(stringToCheck => stringToCheck.Contains(validationHeader)))
根据这个答案; https://stackoverflow.com/a/18767402/1189566
但它说它无法从 string 转换为 bool?
【问题讨论】:
标签: c#