Dyon Dyon - 2 months ago 15
C# Question

How can I reduce the variables used in this code?

I am trying to reduce the amount of variables used in the code below.

Ideally I would like to keep reusing the string variable LatestRipMe without creating the LatestRipMeVersion string[] variable.

Do I need to create an array in order to do 'Skip(1)' and 'First()'?

Can I reach the final value of LatestRipMe more efficiently?

private void RipMeGetLatestVersion_Process()
{
//Get the .json file and save it in LatestRipMe string
LatestRipMe = ClientRipMe.DownloadString("http://www.rarchives.com/ripme.json");

//Create an array from the previously saved string, and skip the first line
LatestRipMeVersion = LatestRipMe.Split(Environment.NewLine.ToCharArray()).Skip(1).ToArray();

//Put the array back in a string, and select only the first line
LatestRipMe = LatestRipMeVersion.First();

//The characters which need to be removed
char[] LatestRipMeTrim = { ' ', ' ', '"', 'l', 'a', 't', 'e', 's', 't', 'V', 'e', 'r', 's', 'i', 'o', 'n', '"', ' ', ':', ' ', '"', '"', ',' };

//Trim the above declared characters
LatestRipMe = LatestRipMe.Trim(LatestRipMeTrim);

//Show the remaining string content in the TextBlock
LatestRipMeVersionText.Text = "Latest RipMe version: " + LatestRipMe;
}

Answer

You can replace

  //Create an array from the previously saved string, and skip the first line
  LatestRipMeVersion = LatestRipMe.Split(Environment.NewLine.ToCharArray()).Skip(1).ToArray();

  //Put the array back in a string, and select only the first line
  LatestRipMe = LatestRipMeVersion.First();

with

  LatestRipMe = LatestRipMe.Split(Environment.NewLine.ToCharArray())[1];

or even

  LatestRipMe = LatestRipMe
           .Split(Environment.NewLine.ToCharArray())[1]
           .Trim(new char[] { ' ', 'a', 'b' });  // etc ...

Opinion:
Style wise, that is ugly, difficult to debug and and will throw an exception the site doesn't return what you expect (no internet connection, etc). I don't really understand the desire to replace your clear, documented step by step code just to reduce the number of variables unless its for a programming challenge.