单个linq中的多重条件

时间:2013-08-29 10:09:43

标签: vb.net linq optimization

我正在迭代控件,它有多行,每行都有一个标签,只是实现了以下的linq。我可以将以下查询优化为单个查询吗?

 Dim xCheckTag As String = If((From xTag As Row In Sheet1.Rows Where xTag.Tag = "FtpHeader").ToArray.Length > 0, "FtpHeader", _
                            If((From xTag As Row In Sheet1.Rows Where xTag.Tag = "MailHeader").ToArray.Length > 0, "MailHeader", _
                            If((From xTag As Row In Sheet1.Rows Where xTag.Tag = "GoogleHeader").ToArray.Length > 0, "GoogleHeader", _
                            If((From xTag As Row In Sheet1.Rows Where xTag.Tag = "NetworkHeader").ToArray.Length > 0, "NetworkHeader", String.Empty))))

2 个答案:

答案 0 :(得分:1)

您可以使用FirstOrDefault作为 Dominic 建议,但如果没有匹配项,则会返回null而不是String.Empty。我会使用DefaultIfEmpty返回正确的默认值:

Dim tags = {"FtpHeader","MailHeader","GoogleHeader","NetworkHeader"}
Dim xCheckTag = tags.Where(Function(tag) Sheet1.Rows.Cast(Of Row)().Any(Function(xTag) xTag.Tag = tag)) _
                    .DefaultIfEmpty(String.Empty) _
                    .First()

答案 1 :(得分:0)

FirstOrDefaultAny结合使用:

Dim tags = {"FtpHeader","MailHeader","GoogleHeader","NetworkHeader"}
Dim xCheckTag = If(tags.FirstOrDefault(Function(tag) Sheet1.Rows.OfType(Of Row).Any(Function(xTag) xTag.Tag = tag)), String.Empty)