2017-08-26 46 views
-1

我知道我可以測試的條件和運行這樣的代碼情況發現:添加字符串數組,如果使用合併操作

if (scrapedElement.Contains(".html") 
    string [] Test = new string[] { scrapedElement, string.empty } 
else 
    string [] Test = new string[] { scrapedElement } 

不過,我想如果可能的話做一個單行。同樣的事情也該(這是全系列的,我希望它的工作代碼):

File.AppendAllLines(@"C:\Users\DJB\Documents\Visual Studio 2017\Projects\TempFiles\WebScraperExport.csv", new[] { (scrapedElement.Contains(".html") ? scrapedElement, string.Empty : scrapedElement)}); 

我在做什麼是一個Web刮板是然後保存在一個Excel文件中的文件。對於每個找到鏈接的元素,在它後面添加一個空行,如果不是隻添加該元素。

+0

那麼,有什麼問題呢?有沒有錯誤? – mmushtaq

+0

是的,我得到該代碼編譯錯誤。 – djblois

+0

這個錯誤是由於這個陳述'? scrapedElement,string.Empty:scrapedElement'因爲你不能以這種方式添加合併操作符。 – mmushtaq

回答

0

這編譯爲我和應該做的事情你需要

using System; 

public class Test 
{ 
    public static void Main() 
    { 
     string scrapedElement = "test test .html test"; 
     string [] Test = scrapedElement.Contains(".html") 
          ? new string[] { scrapedElement, string.Empty } 
          : new string[] { scrapedElement }; 
    } 
} 

另一種選擇,將處理您的案件沒有重複(但不包括1班輪!)

using System; 

public class Test 
{ 
    public static void Main() 
    { 
     string scrapedElement = "test test .html test"; 
     string [] Test =new string[scrapedElement.Contains(".html")?2:1]; 
     Test[0] = scrapedElement; 

    } 

} 
+0

謝謝Marcin,我正在考慮做我只是認爲它仍然重複代碼,新的字符串[] {scrapedElement部分。有什麼方法可以不重複嗎? – djblois

+0

我不知道你的代碼的其餘部分是什麼樣子,如果你必須專門使用數組。我建議考慮更多的彈性數據類型,如列表或向量,它應該更容易,因爲無論如何你都要附加字符串,並選擇附加空字符串。最後你可以得到一個數組我們的列表。 –

+0

@djblois你也可以這樣刪除'string'規範:'string [] Test = scrapedElement.Contains(「。html」)? new [] {scrapedElement,string.Empty}:new [] {scrapedElement};' –