过滤DataSet

我有一个充满了客户的DataSet。 我想知道是否有任何方法来过滤数据集,只获取我想要的信息。 例如,为CostumerID = 1的客户获取CostumerNameCostumerAddress

可能吗?

您可以使用DataTable.Select

 var strExpr = "CostumerID = 1 AND OrderCount > 2"; var strSort = "OrderCount DESC"; // Use the Select method to find all rows matching the filter. foundRows = ds.Table[0].Select(strExpr, strSort); 

或者您可以使用DataView

 ds.Tables[0].DefaultView.RowFilter = strExpr; 

更新我不确定为什么要返回DataSet。 但我会采用以下解决方案:

 var dv = ds.Tables[0].DefaultView; dv.RowFilter = strExpr; var newDS = new DataSet(); var newDT = dv.ToTable(); newDS.Tables.Add(newDT); 

没有提到合并?

 DataSet newdataset = new DataSet(); newdataset.Merge( olddataset.Tables[0].Select( filterstring, sortstring )); 

以上情况非常接近。 这是我的解决方案:

 Private Sub getDsClone(ByRef inClone As DataSet, ByVal matchStr As String, ByRef outClone As DataSet) Dim i As Integer outClone = inClone.Clone Dim dv As DataView = inClone.Tables(0).DefaultView dv.RowFilter = matchStr Dim dt As New DataTable dt = dv.ToTable For i = 0 To dv.Count - 1 outClone.Tables(0).ImportRow(dv.Item(i).Row) Next End Sub