-1

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.

djblois
  • 963
  • 1
  • 17
  • 52
  • So what's the problem? Is there any error? – mmushtaq Aug 26 '17 at 18:56
  • Yeah I get a compile error with that code. – djblois Aug 26 '17 at 18:59
  • The error would be due to this statement `? scrapedElement, string.Empty : scrapedElement` because you can't add coalesce operator in this way. – mmushtaq Aug 26 '17 at 19:25
  • `".html"` doesn't seem like a very safe way to find all links. If all links have closing anchor tag `<\a>` then you can add new line after all of them at once `text = text.Replace("<\\a>", "<\\a>\n")` – Slai Aug 26 '17 at 22:04

1 Answers1

0

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;

    }

}
  • Thank you Marcin, I was thinking about doing that I just thought it was still repeating code, the new string[] { scrapedElement part. Is there any way to not repeat that? – djblois Aug 26 '17 at 18:58
  • I am not sure how the rest of Your code looks like and if You have to use arrays specifically. I would recommend considering more elastic data types, like lists or vectors, it should be then easier, as You'd append the string anyhow and choose to append empty string or not. Finally You can get an array our of the list. – Marcin Gałczyński Aug 26 '17 at 19:04
  • @djblois You can also remove the `string` specification like this: `string[] Test = scrapedElement.Contains(".html") ? new[] { scrapedElement, string.Empty } : new[] { scrapedElement };` – Salah Akbari Aug 26 '17 at 19:05