我正在使用SQL Server数据库在vb.net Windows窗体应用程序中构建一个简单的搜索工具, 用户将输入一个唯一的ID,并将看到显示状态的结果。
Public Class IStatus
Public Property Id As String
Public Property Status As String
Public Sub New(ByVal Id As String, ByVal Status As String)
Id = Id
Status = Status
End Sub
End Class
我正在做的是在List(Of IStatus)中填充数据库中的行 现在,我想使用linq从数据表中过滤行,到目前为止,我已经完成了以下操作:
Public Function GetDS() As List(Of IStatus)
Dim sRows As New List(Of IStatus)
Dim dr As SqlDataReader = GetDataReader()
If dr.HasRows Then
Using dt As New DataTable
dt.Load(dr)
totRows = dt.Rows.Count
If (totRows > 1) Then
For Each drow As DataRow In dt.Rows
Dim sRow As New IStatus(drow(0).ToString(), drow(1).ToString())
sRows.Add(sRow)
Next
'Trying to filter the data with linq conditions here ...
Dim uniqRows = sRows.Where(Function(p) p.Status = "Open" Or p.Status = "Closed" Or p.Status = "Unknown").ToList
sRows = uniqRows.ToList
Else
Dim sRow As New IStatus(dt.Rows(0)(0).ToString, dt.Rows(0)(1).ToString)
sRows.Add(sRow)
End If
Return sRows
End Using
End If
End Function
我有以下对象的列表:
IStatus
-----------
Id
Status
以下是我想要实现的示例数据和过滤:
例如数据:
-----------------
Id Status
-----------------
1 Open
1 Open
1 Closed
返回所有行,因为状态值之一不同。
Id Status
-----------------
1 Open
1 Open
1 Open
仅返回第一行,因为所有状态值都相同。
Id Status
-----------------
1 Unknown
1 Open
1 Open
如果任一状态为“未知”,则返回“未知”行。
谢谢。
答案 0 :(得分:0)
您可以使用findall函数来过滤通用列表
Public Class IStatus
Public Property Id As String
Public Property Status As String
Public Sub New(ByVal Id_ As String, ByVal Status_ As String)
Id = Id_
Status = Status_
End Sub
End Class
Function Createlist() As List(Of IStatus)
Dim L1 = New List(Of IStatus)()
L1.Add(New IStatus("1", "open"))
L1.Add(New IStatus("1", "open"))
L1.Add(New IStatus("1", "closed"))
L1.Add(New IStatus("1", "closed"))
L1.Add(New IStatus("1", "closed"))
L1.Add(New IStatus("2", "open"))
L1.Add(New IStatus("2", "open"))
L1.Add(New IStatus("2", "closed"))
L1.Add(New IStatus("2", "closed"))
L1.Add(New IStatus("2", "closed"))
Return L1
End Function
Sub main()
Dim l1 = Createlist().FindAll(Function(x As IStatus) x.Id = "1")
For Each ii In l1
With ii
Console.WriteLine(.Id & "- " & .Status)
End With
Next
Stop
End Sub