代码之家  ›  专栏  ›  技术社区  ›  Steve

如何处理LINQ Select语句中的异常

  •  4
  • Steve  · 技术社区  · 15 年前

     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());
    

    所以,有时会失败的计算。我不想输入空值,然后用另一个Where语句过滤掉它,垃圾值同样是不可接受的。有人知道如何处理干净吗?谢谢。

    编辑:double-Select语句有一个很好的理由。为了简洁起见,对这个示例进行了编辑

    2 回复  |  直到 15 年前
        1
  •  2
  •   devuxer    15 年前

    我不清楚如果你是说,你不想用 null 对于 FooThing 无效的 对于整个匿名类型的对象。无论如何,这是否符合要求?

     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
  •  1
  •   R. Martinho Fernandes    15 年前

    this one )用于可能返回值,也可能不返回值,而不是空值或垃圾值的计算。看起来是这样的:

    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);