Get string from array or set default value in a one liner
I suggest you create a method for this. which will accept two inputs of type string(representing the input string) and an integer(represents the specified index), and should return the split value if the specified index is available, else it will return an empty string:
string GetSubstring(string input, int index)
{
string returnValue = String.Empty;
string[] substrings = input.Split(new[] { "-" }, StringSplitOptions.RemoveEmptyEntries);
returnValue = substrings.Length > index ? substrings[index] : returnValue;
return returnValue;
}
Here is a working example for your reference
Well, you can try Linq:
using System.Linq;
...
string thirdValue = value.Split('-').ElementAtOrDefault(2) ?? string.Empty;
However, your code has a drawback: you constantly Split
the same string. I suggest extracting value.Split('-')
:
string value = "One - Two"
var items = value.Split('-');
string firstValue = items.ElementAtOrDefault(0) ?? string.Empty;
string secondValue = items.ElementAtOrDefault(1) ?? string.Empty;