-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)});

我正在做的是一个网络爬虫,然后将文件保存在一个 excel 文件中。对于它找到的每个链接元素,如果不只是添加元素,请在其后添加一个空行。

4

1 回答 1

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-liner!)

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;

    }

}
于 2017-08-26T18:56:35.747 回答