Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get string from array or set default value in a one liner

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.

like image 526
Roy Berris Avatar asked Jul 30 '19 11:07

Roy Berris


People also ask

What is the default value of string variable select one?

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.

How do you set a list to default values?

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.

What is the default value of string array in C#?

The array indexes start at zero. The default value of numeric array elements are set to zero, and reference elements are set to null .


2 Answers

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;
like image 180
Dmitry Bychenko Avatar answered Nov 08 '22 18:11

Dmitry Bychenko


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

like image 44
sujith karivelil Avatar answered Nov 08 '22 18:11

sujith karivelil