views:

151

answers:

3
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?

A: 

As long as you are not going to use it with LinqToSQL or EF you can create your own extension method that wraps the exception and tells you the value of the string.

klausbyskov
A: 

In this case a Where clause may be appropriate to filter out the length you're looking for:

var trimmed = myStringArray
        .Where( s => s.Length >= 10 )
        .Select( s => s.Substring( 0, 10 ) );

EDIT
Just re-read the question realized the OP is looking for exception handling to see what strings were not long enough. Assuming you don't care what strings are long enough, then the solution provided will work.

Metro Smurf
+2  A: 

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 ...})

Hightechrider
I was just using method block syntax on something else yesterday and didn't even make the connection. Thanks!
ifwdev