sabato 25 agosto 2012

How To Skip Linq Exception

 

Implement static IEnumerable<T> function to skip Exception when run a query.

This function return valid items only.

  1. public static class LINQException {
  2.     public static void TryExample() {
  3.         var LsWithEx = from p in Enumerable.Range(0, 10) select int.Parse("dsfksdj");
  4.         var LsSkipEx = (from p in Enumerable.Range(0, 10) select int.Parse("dsfksdj")).SkipExceptions();
  5.     }
  6.  
  7.     public static IEnumerable<T> SkipExceptions<T>(this IEnumerable<T> values)
  8.     {
  9.         using (var enumerator = values.GetEnumerator())
  10.         {
  11.             bool next = true;
  12.             while (next)
  13.             {
  14.                 try
  15.                 {
  16.                     next = enumerator.MoveNext();
  17.                 }
  18.                 catch
  19.                 {
  20.                     continue;
  21.                 }
  22.  
  23.                 if (next) yield return enumerator.Current;
  24.             }
  25.         }
  26.     }
  27.     
  28.     }

 

I hope this help Smile

Nessun commento: