Try a Linq query

Is there a neat way to ignore exceptions in Linq? I., let's say, I have a class ObjectAthat takes a string parameter in its constructor, and some verification happens inside the constructor - this means that if the string does not have the required format, the constructor will throw. With the following code, I would get a list ObjectAfrom 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 linq line, a la (pseudo code is suitable ...)

var result = ListOfFiles.Select(n => try {new ObjectA(n)}).ToList();
+4
source share
1 answer

try using the scope in the method Select()and Where()to filter the zero outputs:

        var result = ListOfFiles.Select(_s =>
            {
                try
                {
                    return new ObjectA(_s);
                }
                catch (Exception)
                {
                    return null;
                }

            }).Where(x => x != null).ToList();
+3
source

Source: https://habr.com/ru/post/1526929/


All Articles