C# - Filtering with DataView
I have a dataset full of order information and I am trying to filter the datase开发者_Python百科t with DataView.
This is what I have so far. This returns all the columns in the DataSet.
DataTable orders = dataSet.Tables[0];
EnumerableRowCollection<DataRow> query = from order in orders.AsEnumerable()
where order.Field<Int16>("OrderID") = 2
select order;
DataView view = query.AsDataView();
What I want to do is that the query only return some columns not all of them. What do I do?
Use anonymous types in your query:
DataTable orders = dataSet.Tables[0];
EnumerableRowCollection<DataRow> query = from order in orders.AsEnumerable()
where order.Field<Int16>("OrderID") = 2
select new { Property1, Property2 };
DataView view = query.AsDataView();
Maybe you should consider actually using the capabilities of the DataView
itself instead of using a sort-of roundabout LINQ solution:
var filter = new DataView(orders);
filter.RowFilter = "OrderID = 2";
var resultTable = filter.ToTable(false, "Column1", "Column2", "Column3");
The ToTable()
method allows you to specify an arbitrary list of columns to create a new table from. Of course you can still wrap the result table in another DataView if you need to return that instead of a table:
var resultView = new DataView(resultTable);
精彩评论