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.
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");
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"));
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