Zippy Zippy - 9 months ago 74
C# Question

C# string split - index out of bounds

My brain is tired right now and cant come up with a simple solution to this.

var res = error.Split('|');
return String.Format("Name: {0} <br /> Email: {1}", res[0] , res[1]);

If there is no | split then it throws an error what would be a quick and graceful way to just throw in a default "No Name" or pass on it. I only care about positions [0] and [1].

Sample Data

Tom |
Tom |
Tom | | texas

I need a redbull.

Answer Source

You can use the ElementAtOrDefault() extension method from the System.Linq namespace combined with the null-coalescing operator (??) for an elegant solution:

return String.Format("Name: {0} <br /> Email: {1}", 
    res.ElementAtOrDefault(0) ?? "No name", 
    res.ElementAtOrDefault(1) ?? "No email");