2015-10-13 64 views
0

我試圖解析出這種具有超過8000行硬編碼數據驗證的單一方法。其中大部分是相同的,爲數據源中的不同字段重複邏輯。如何遍歷列表而其內容包含一個子值?

很多,它看起來是這樣的(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

回答

1

你的意思是這樣的嗎?

while (lines.Any(x => x.Contains(validationHeader))) 

這將檢查validationHeader是否是列表中任何字符串的一部分。

我也試過這個;

while (lines.Where(stringToCheck => stringToCheck.Contains(validationHeader))) 

這是行不通的,因爲你的情況LINQ的Where方法將返回IEnumerable<string>。並且while循環需要一個布爾謂詞。 IEnumerable不能是truefalse,因此編譯器正在抱怨。

+0

謝謝!這解決了我的問題,現在要弄清楚我的其他邏輯問題 – sab669