24

I have a DataSet full of costumers. I was wondering if there is any way to filter the dataset and only get the information I want. For example, to get CostumerName and CostumerAddress for a costumer that has CostumerID = 1

Is it possible?

svick
  • 236,525
  • 50
  • 385
  • 514
Erika
  • 399
  • 2
  • 3
  • 8

3 Answers3

46

You can use 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);  

Or you can use DataView:

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

UPDATE I'm not sure why you want to have a DataSet returned. But I'd go with the following solution:

var dv = ds.Tables[0].DefaultView;
dv.RowFilter = strExpr;
var newDS = new DataSet();
var newDT = dv.ToTable();
newDS.Tables.Add(newDT);
Kamyar
  • 18,639
  • 9
  • 97
  • 171
  • @Kamyar - The thing is that I need the result for the filtering to be in DataSet format. How do I do? – Erika May 15 '11 at 10:47
  • @Erika: You can use dataview's `ToTable` method to convert dataview to datatable. `var dv = ds.Tables[0].Defaultview; dv.RowFilter=...; var dt = dv.ToTable();` Why would you want it to be a dataset? – Kamyar May 15 '11 at 10:51
  • @Kamyar - The customer wants it to be dataset :S, is it possible to convert it to DataSet again? – Erika May 15 '11 at 11:02
  • @Kamyar - Thank you very much. It works great. The only thing that iam wondering about is if its possible to edit the filtering so that only two columns in the dataset shown and not all of the columns. I only nead CustomerName and CustomerAdress. How can I filter the columns to? – Erika May 16 '11 at 09:23
6

No mention of Merge?

DataSet newdataset = new DataSet();

newdataset.Merge( olddataset.Tables[0].Select( filterstring, sortstring ));
Eric
  • 389
  • 5
  • 8
1

The above were really close. Here's my solution:

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
oaksong
  • 47
  • 7