Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
Generic Type Foreach and Exceptions
//Title of this code //Rextester.Program.Main is the entry point for your code. Don't change it. //Compiler version 4.0.30319.17929 for Microsoft (R) .NET Framework 4.5 using System; using System.Collections.Generic; using System.Linq; namespace Rextester { public class Program { private static IEnumerable<T> SkipExceptions<T>( IEnumerable<T> values) { using (var enumerator = values.GetEnumerator()) { var next = true; while (next) { try { next = enumerator.MoveNext(); } catch(Exception ex) { continue; } if (next) yield return enumerator.Current; } } } private static int OneIsBadMethod(int i) { if (i == 1) { throw new Exception("one is bad"); } return i; } private static IEnumerable<int> OneIsBadForeach(IEnumerable<int> i) { foreach (var i1 in i) { yield return OneIsBadMethod(i1); } } private static IEnumerable<int> OneIsBadSelect(IEnumerable<int> i) { return i.Select(OneIsBadMethod); } public static void Main(string[] args) { var ints = new[]{0, 1, 2, 3}; var countForeach = SkipExceptions(OneIsBadForeach(ints)).Count(); var countSelect = SkipExceptions(OneIsBadSelect(ints)).Count(); Console.WriteLine("count with foreach: " + countForeach); Console.WriteLine("count with select: " + countSelect); } } }
run
|
edit
|
history
|
help
0
Multidimensional Arrays
octalofint
Frase
jkloikujyt5r4e3wsxdf
v v
Messages
C# - MD5Hash
Reverse a string
Linq - When using FirstOrDefault, make sure to check for null result
linq sort