【问题标题】:how to deal with exception in LINQ Select statement如何处理 LINQ Select 语句中的异常
【发布时间】:2010-01-29 09:16:39
【问题描述】:

我有一个如下的 LINQ 查询

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

因此,CalculationThatCanFail 有时会抛出。我不想将 null 放入,然后稍后用另一个 Where 语句将其过滤掉,垃圾值同样是不可接受的。有谁知道如何干净地处理这个?谢谢。

编辑:双 Select 语句有充分的理由。为简洁起见,对这个示例进行了编辑

【问题讨论】:

    标签: c# linq


    【解决方案1】:

    我不清楚您的意思是,您不想将null 用于FooThing,或者您不想将null 用于整个匿名键入的对象。无论如何,这是否符合要求?

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

    【讨论】:

    • 是的,我想知道是否有办法避免 .Where(p => p != null)
    • @Steve,哦,好吧。我不完全确定,但我唯一能想到的 LINQ 就是使用 ForEach() 扩展方法,但即便如此,您最终还是会手动构建某种集合/可枚举,而不是拥有LINQ 为您构建它。如果我可以问,您对Where 子句的反对意见是什么?
    【解决方案2】:

    对于这些情况,我使用 Maybe 类型(类似于 this one)来进行可能返回或不返回值的计算,而不是 null 或垃圾值。它看起来像这样:

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

    【讨论】:

      猜你喜欢
      • 2020-08-22
      • 2015-07-19
      • 1970-01-01
      • 2014-02-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多