Add string to array if condition found using coalesce operator

153 views Asked by At

I know I can test the condition and run the code like this:

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

However, I want to do it in a single line if possible. Something similar to this (this is the full line of code that I want it to work in):

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

What I am doing is a web scraper that then saves the files in an excel file. For every element it finds that is a link, add a blank line after it, if not just add the element.

1

There are 1 answers

3
Marcin Gałczyński On

This compiled for me and should do what You need

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

Another alternative that will handle Your case without duplication (but not 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;

    }

}