tags:

views:

78

answers:

2

Hello, 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, the CalculationThatCanFail throws sometimes. I don't want to put null in and then filter that out with another Where statement later, and a junk value is equally unacceptable. Does anyone know how to handle this cleanly? Thanks.

EDIT: There's a good reason for the double Select statement. This example was edited for brevity

+1  A: 

For these situations I use a Maybe type (similar to this one) for calculations that may or may not return a value, instead of nulls or junk values. It would 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);
Martinho Fernandes
+1  A: 

I'm not clear from question if you mean, you don't want to use null for FooThing or you don't want to use null for the entire anonymously typed object. In any case, would this fit the bill?

 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());
DanM
yeah, I was wondering if there was anyway to avoid the .Where(p => p != null)
Steve
@Steve, Oh okay. I'm not entirely sure, but the only thing I can think of with LINQ would be to use the `ForEach()` extension method, but even then, you'll end up manually constructing a collection/enumerable of some sort, rather than having LINQ build it for you. If I may ask, what is your objection to the `Where` clause?
DanM