【问题标题】:Querying datatable.AsEnumerable with LINQ使用 LINQ 查询 datatable.AsEnumerable
【发布时间】:2013-06-25 21:25:34
【问题描述】:

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

规则 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 条规则,如果我为规则一返回了一行,我使用第一个查询返回的价格,如果第一个查询没有返回任何内容,那么我继续执行第二个规则并使用价格从第二个开始,如有必要,请转到第三个和第四个...

但这似乎有点冗长,我知道所有可能的场景以及我想检查场景的顺序,有没有办法将这些组合起来并通过一个查询找出价格?

谢谢

【问题讨论】:

    标签: vb.net linq datatable


    【解决方案1】:

    您的问题不是 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
    

    【讨论】:

    • 谢谢,single应该是FirstOrDefault,我已经编辑了问题,但是你的建议不起作用,因为多个场景可以同时存在,我只需要依次检查它们,如果有符合规则 1 的行使用它,如果不继续使用规则 2 等。
    猜你喜欢
    • 2011-04-26
    • 2012-09-09
    • 2010-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多