开发者

LINQ Iterator Exception Handling

开发者 https://www.devze.com 2022-12-22 08:03 出处:网络
var trimmed = myStringArray.Select(s => s.Substring(0, 10)); If one of the strings isn\'t 10 characters long I\'d get an ArgumentOutOfRangeException.
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 a开发者_JAVA技巧nd 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 ...})


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消