Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Try within Linq query [duplicate]

Tags:

c#

exception

linq

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();
like image 944
EluciusFTW Avatar asked Oct 01 '22 14:10

EluciusFTW


1 Answers

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.

like image 75
Felipe Oriani Avatar answered Oct 16 '22 20:10

Felipe Oriani