C# 如果使用合并运算符发现条件,则将字符串添加到数组中

C# 如果使用合并运算符发现条件,则将字符串添加到数组中,c#,if-statement,web-scraping,coalescing,C#,If Statement,Web Scraping,Coalescing,我知道我可以测试条件并像这样运行代码: if (scrapedElement.Contains(".html") string [] Test = new string[] { scrapedElement, string.empty } else string [] Test = new string[] { scrapedElement } 但是,如果可能的话,我想在一行中完成它。类似于此(这是我希望它使用的完整代码行): 我正在做的是一个网页刮板,然后将文件保存在e

我知道我可以测试条件并像这样运行代码:

if (scrapedElement.Contains(".html")
     string [] Test = new string[] { scrapedElement, string.empty }
else 
     string [] Test = new string[] { scrapedElement }
但是,如果可能的话,我想在一行中完成它。类似于此(这是我希望它使用的完整代码行):


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

这是为我编写的,应该可以满足您的需要

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 };
    }
}
另一种可以处理您的案例而不重复的替代方案(但不是单行扫描!)


那有什么问题?有什么错误吗?是的,我得到一个编译错误的代码。错误将是由于这句话
?scrapedElement,string.Empty:scrapedElement
,因为无法以这种方式添加合并运算符。
“.html”
似乎不是查找所有链接的非常安全的方法。如果所有链接都有结束锚标记
,那么您可以在所有链接之后立即添加新行
text=text。替换(“,”\n”)
谢谢Marcin,我正在考虑这样做,我只是认为它仍然在重复代码,新字符串[]{scrapedElement部分。有没有办法不重复这一点?我不确定您的代码的其余部分是什么样子,也不确定您是否必须特别使用数组。我建议考虑更具弹性的数据类型,如列表或向量,这样应该更容易,因为您可以任意附加字符串,并选择是否附加空字符串。最后,您可以n获取列表的数组。@djblois您也可以删除
string
规范,如下所示:
string[]Test=scrapedElement.Contains(“.html”)?new[]{scrapedElement,string.Empty}:new[]{scrapedElement};
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 };
    }
}
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;

    }

}