How to handle exception in LINQ Select expression

I have a LINQ query as follows

m_FOO = rawcollection.Select(p=> p.Split(' ')).Select(p => { int thing = 0; try { thing = CalculationThatCanFail(p[1]); } catch{} return new { Test = p[0], FooThing = thing}; }) .GroupBy(p => p.Test) .ToDictionary(p => p.Key, s => s.Select(q => q.FooThing).ToList()); 

So, CalculationThatCanFail throws sometimes. I don't want to type null and then filter it with another Where statement, and the spam value is equally unacceptable. Does anyone know how to handle this? Thanks.

EDIT: There is a good reason for the double select statement. This example has been edited for brevity.

+4
source share
2 answers

I do not understand, if you mean, you do not want to use null for FooThing or you do not want to use null for the whole anonymous typed object. In any case, does this correspond to the vector?

  m_FOO = rawcollection.Select(p=> p.Split(' ')).Select(p => { int thing = 0; try { thing = CalculationThatCanFail(p[1]); return new { Test = p[0], FooThing = thing}; } catch { return null; } }) .Where(p => p != null) .GroupBy(p => p.Test) .ToDictionary(p => p.Key, s => s.Select(q => q.FooThing).ToList()); 
+2
source

In these situations, I use the Maybe type (similar to this one ) for calculations that may or may not return a value, rather than zeros or unwanted values. It will look like this:

 Maybe<int> CalculationThatMayHaveAValue(string x) { try { return CalculationThatCanFail(x); } catch { return Maybe<int>.None; } } //... var xs = ps.Select(p => { Maybe<int> thing = CalculationThatMayHaveAValue(p[1]); return new { Test = p[0], FooThing = thing}; }) .Where(x => x.FooThing.HasValue); 
+1
source

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


All Articles