var trimmed = myStringArray.Select(s => s.Substring(0, 10));
If one of the strings isn't 10 characters long I'd get an ArgumentOutOfRangeException.
In this case its fairly trivial to find out and I know I can do
s.Substring(0, Math.Min(10, s.Length))
With more complex object construction errors like this aren't always easy to see though. Is there a way to see what string wasn't long enough via exception handling?
Create a method that does the complex transformation that can throw exceptions and call it from the lambda. e.g. .Select(s => complexMethod(s))
string complexMethod(string s)
{
try
{
...
return ...
}
catch
...
}
Now you can log the exception within the catch block before re-throwing, or use Exception.Data to add information to it before re-throwing, or wrap it in a custom exception with the information you need. Remember to use just 'throw' when you re-throw it if it's not a custom exception.
You can also put the method body inline in the lambda: .Select(s => { ... return ...})
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