So we have ??
to parse its right-hand value for when the left hand is null.
What is the equivalent for a string[]
.
For example
string value = "One - Two"
string firstValue = value.Split('-')[0] ?? string.Empty;
string secondValue = value.Split('-')[1] ?? string.Empty;
Above example would still crash if we would try to get a third index or if string value = "One"
. Because it is not null but IndexOutOfRangeException
is thrown.
https://docs.microsoft.com/en-us/dotnet/api/system.indexoutofrangeexception
So what is a one-line solution to tackle the above problem? I'd like to avoid the try-catch scenario because this gives ugly code.
I want to get value out of a string[]
with a string.Empty
as a backup value so my string
is never null
.
The object and string types have a default value of null, representing a null reference that literally is one that does not refer to any object.
Using asList() allows you to populate an array with a list of default values. This can be more efficient than using multiple add() statements to add a set of default values to an ArrayList.
The array indexes start at zero. The default value of numeric array elements are set to zero, and reference elements are set to null .
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;
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With