Linq安全检查

时间:2016-04-29 03:41:52

标签: vb.net linq

我正在处理以下代码:

Dim xyzTotal As Decimal?
Dim ins = Recins

If ins IsNot Nothing Then
    For Each obj In ins
        If obj.DCovers isNot Nothing Then
            For Each cover In obj.DCovers
                If cover.Event.Code.ToUpper().Contains("XYZ") Then
                    xyzTotal += cover.Value
                End If
            Next
        End If  
    Next
End If
Return xyzTotal

为此写了以下LINQ语句:

Dim xyzTotal As Decimal?
Dim ins = Recins

If ins IsNot Nothing Then
    For Each obj In ins
        obj.DCovers.Where(Function(x) x.Event.Code.ToUpper().Contains("TPD")).ToList().ForEach(Function(y) xyzTotal = xyzTotal + y.Value)
    Next

End If
Return xyzTotal

如何将检查(就像我在上面的代码中所做的那样)放到我的LINQ语句中,以确保在任何值不存在时它应该产生错误。单行LINQ(而不是上面的Foreach)会好得多。

2 个答案:

答案 0 :(得分:0)

在VB 14中,您可以使用空条件运算符( <div class="container"> <form action="home.html" id="login-form" method="post" onsubmit="return validateOnSubmit()"> <p class="form-header">Sign In</p> <span>Username</span> <br/> <input type="text" name="username" id="username" autocomplete="off" required/> <br/> <br/> <span>Password</span> <br/> <input type="password" name="login-password" id="login-password" onkeyup="return validate()" required/> <p id="alert">Password should more than 4 characters!</p> <br/> <br/> <input type="checkbox" name="rememberMe" class="rememberMe" id="rememberMe"/> <label for="rememberMe">Remember Me</label> <br/> <br/> <input type="submit" id="submit" value="Sign In"/> <br> <br> <div id="options"> <a href="register.html">Not registered ?</a> </div> <input type="hidden" name="operation" value="login"> </form> </div> <script type="text/javascript" src="js/validate.js"></script> </body> ):

?.

Visual Basic .NET - 14 Top Improvements in Visual Basic 14

答案 1 :(得分:0)

使用Where函数过滤掉任何obj属性为DCovers的元素。

您还可以使用Aggregate函数创建元素的总和。

Dim xyzTotal As Decimal?
Dim ins = Recins

If ins IsNot Nothing Then
    xyzTotal = ins _
        .Where(Function(x) x.DCovers IsNot Nothing) _
        .SelectMany(Function(x) x.DCovers) _
        .Where(Function(x) x.Event.Code.ToUpper().Contains("XYZ")) _
        .Aggregate(New Decimal?, Function(total, current) If(total, 0D) + current.Value)
End If

Return xyzTotal

请注意,当您使用Aggregate函数时,您需要以空值(New Decimal?)开头,然后在执行求和时将其合并为零,因为空值加上非值-null值导致空值。

正如@ har07所说,如果您使用的是Visual Studio 2015,还可以在ins变量上使用空条件运算符:

xyzTotal = ins?.Where(Function(x) x.DCovers IsNot Nothing)...