Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# string split - index out of bounds

Tags:

string

c#

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 | [email protected]
Tom
Tom | [email protected]
Tom | [email protected] | texas

I need a redbull.

like image 478
Zippy Avatar asked Jan 15 '13 17:01

Zippy


2 Answers

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");
like image 177
luksan Avatar answered Sep 21 '22 12:09

luksan


How about you add an extension method to IList<T>:

public static T IndexOrDefault<T>(this IList<T> list, int index, T defaultValue)
{
    if (index < 0 || index >= list.Count)
    {
        return defaultValue;
    }

    return list[index];
}

Then you can use it like this:

var res = error.Split('|');
return String.Format("Name: {0} <br /> Email: {1}", res[0] , res.IndexOrDefault(1, "No E-mail"));
like image 42
Dan Tao Avatar answered Sep 22 '22 12:09

Dan Tao