使用LINQ查询datatable.AsEnumerable

时间:2013-06-25 21:25:35

标签: vb.net linq datatable

我有一个数据表,我查询以确定某个行是否存在,有几种可能的情况:

规则1:

Dim rt1 As EnumerableRowCollection(Of Double) = From row In dtCh.AsEnumerable() _
Order By row.Field(Of Int64)("ID") Descending
Where (row.Field(Of String)("L_TYPE") = "A" _
And row.Field(Of Int16)("Customer_Type") = 1)
Select row.Field(Of Double)("Price")

If rt1.Any() Then
    return CType(rt1.FirstOrDefault(), Decimal)
End If

规则2:

Dim rt2 As EnumerableRowCollection(Of Double) = From row In dtCh.AsEnumerable() _
Order By row.Field(Of Int64)("ID") Descending
Where (row.Field(Of String)("L_TYPE") = "B" _
And row.Field(Of Int16)("Customer_Type") = 0)
Select row.Field(Of Double)("Price")

If rt2.Any() Then
    return CType(rt2.FirstOrDefault(), Decimal)
End If

并且还有2个规则,如果我为规则1返回了一行,我使用第一个查询返回的价格,如果从第一个查询中没有返回任何内容,那么我转到第二个规则并使用价格从第二个开始,如有必要,继续进行第三个和第四个......

但这似乎有点冗长的方式,我知道所有可能的情况以及我想检查方案的顺序,是否有任何方法将这些结合起来并通过一个查询找出价格?

谢谢

1 个答案:

答案 0 :(得分:2)

您的问题并非100%明确,但似乎您假设只有一个行对应于任何给定的参数,例如A1,B0等。

在你的查询中,你使用any()来确定列表是否包含任何元素,然后尝试返回Single(),这只有在只有一个元素时才有效,那你为什么要使用Enumerable?

最好找一下符合你条件的第一项,并按照你想要的顺序排列你的条件,例如

dtCh.AsEnumerable().OrderBy(Function(Row) Row.Field(Of Int64)("ID")).First(Function(Row) _  
(Row.Field(Of String)("L_TYPE") = "A" And Row.Field(Of Int16)("Customer_Type") = 1) Or _

(Row.Field(Of String)("L_TYPE") = "B" And Row.Field(Of Int16)("Customer_Type") = 0)).Price  
编辑:好的,我找不到你想要的东西。我不知道是否有可能在一个语句中多次查询,但我有一个解决方案,我刚试过哪个有效。它可能不是每个人的口味,但我非常喜欢它。 (希望我知道如何在代码块中缩进和划分空格?!)

Dim Query = dtCh.AsEnumerable().OrderBy(Function(x) x.Id)

Dim Conditions = 
{
    Function(Row) Row.Field(Of String)("L_TYPE") = "A" And _
    Row.Field(Of Int16)("Customer_Type") = 1,
    Function(Row) Row.Field(Of String)("L_TYPE") = "B" And _
    Row.Field(Of Int16)("Customer_Type") = 0
}.ToList()

For Each Condition In Conditions
    Dim Price = Query.FirstOrDefault(Condition)
    If Price IsNot Nothing
        Price.Price 'Get your price here.
        Exit For
    End If
Next
相关问题