Is there a neat way to ignore exceptions in Linq? I.e., lets say I have a class ObjectA
that takes a string parameter in its constructor, and within the constructor there is some validation going on - meaning that if the string does not have the correct format, the constructor will throw. By the following code I would get a List of ObjectA
from a list of strings:
var result = new List<ObjectA>();
foreach (string _s in ListOfFiles) {
try {
ObjectA _A = new ObjectA(_s);
result.Add(_A);
}
catch{}
}
So my question is: Is there a one line linq way, a la (pseudocode coming up ...)
var result = ListOfFiles.Select(n => try {new ObjectA(n)}).ToList();
Considering you are using Linq to objects
, you could try using a scope in the Select()
method and a Where()
to filter the null outputs:
var result = ListOfFiles.Select(_s =>
{
try
{
return new ObjectA(_s);
}
catch (Exception)
{
return null;
}
}).Where(x => x != null).ToList();
Using strategies like this works fine for linq to objects, but linq to sql does not work as the same because, think for yourself, how would you parse it to SQL? There is simple way to do that.
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