How do I limit the number of rows in a datatable? - c#

I generate a DataTable (from non-SQL data) and then use a DataView to filter the records.
I want to limit the number of records in the final record set but can't do this when I generate the DataTable.
I've resorted to deleting rows from the final result set, as per:
DataView dataView = new DataView(dataTable);
dataView.RowFilter = String.Format("EventDate > '{0}'", DateTime.Now);
dataView.Sort = "EventDate";
dataTable = dataView.ToTable();
while (dataTable.Rows.Count > _rowLimit)
dataTable.Rows[dataTable.Rows.Count - 1].Delete();
return dataTable;
Is there a more efficient way to limit the results?

You can use Linq:
Try changing your code to the following:
DataView dataView = new DataView(dataTable);
dataView.RowFilter = String.Format("EventDate > '{0}'", DateTime.Now);
dataView.Sort = "EventDate";
dataTable = dataView.ToTable();
while (dataTable.Rows.Count > _rowLimit)
{
dataTable = dataTable.AsEnumerable().Skip(0).Take(50).CopyToDataTable();
}
return dataTable;
You'll need namespace: System.Linq and System.Data

Can you add a column which will be similar like rowcount 1,2,3
Something like incrementing as you add rows from your Non-SQL data to the datatable.
Probably after that you can use
DataRow[] rows1 = dTable.Select(" RowIncrement < 50", "EventDate ASC");
RowIncrement is the column which would be something like ROWNUM

Try copying the top x rows from one datatable into a new one.
dataTable.AsEnumerable().Take(50).CopyToDataTable(newdataTable)
and then use that.

Related

find and display datarows in datagridview

I faced to issue of displaying datarows from DataTable from DataSet. I used a temporary table. I found rows that I need by id and copy it to temporary table and then diplay in DataGridView. Is there any way to find and display rows that I need in DataGridView directly from DataTable from DataSet without using any temporary DataTable's? I've tried to do this by hiding and unhiding rows in DataGridView, but sadly it didn't worked out
private DataTable tblFiltered =
ds.Tables("GRAPHICS").AsEnumerable().Where(row =>
row.Field<int>("GRAPHIC_ID") == graphId && row.Field<int>
("GRAPHIC_ID")).CopyToDataTable;
Assuming that DataSet 'ds' containing Table 'GRAPHICS',We can use DataView to Display filtered records in DataGridView. Ex.
int graphId = 2; //Assuming
DataView dv = ds.Tables["GRAPHICS"].AsDataView();
dv.RowFilter = "GRAPHIC_ID = " + graphId; //RowFilter :: Expression used to filter which rows are viewed !!
dataGridView.DataSource = dv.ToTable();
You can use filter
(DatagridView.DataSource as DataTable).DefaultView.RowFilter = string.Format("GRAPHIC_ID= '{0}'", graphId);

Selecting a row from a particular column datatable without LINQ

My DataTable has the columns - Id, Name, Address. I need to select the column Address only WHERE ID = 7. How do I do this ? No LINQ please.
I was thinking of this -
DataView view = new DataView(MyDataTable);
DataTable distinctValues = view.ToTable(true, "ColumnA");
Now you can select.
DataRow[] myRows = distinctValues.Select();
//Get the desired answer by iterating myRows.
Is there a simpler way ?
thanks.
Well if you don't want to use LINQ, you can use a simple foreach loop:
DataTable distinctValues = view.ToTable(true, "ColumnA");
var myRows = new List<DataRow>();
foreach(DataRow row in distinctValues.Rows)
{
if(row["Id"].ToString() == "7") myRows.Add(row);
}

Dataset Sorting using C# on a column with Datetime datatype

I am having a dataset (Dataset ds) and below you can find the field with demo data inside the dataset.
In my Dataset , their is column with name Date (Datatype- DateTime) and i want to sort this column.I cant do the sorting from SQl because the Dataset is a merge of 2 Different Dataset.
Please help me that how i do the sorting in dataset.
Date Volume
07/19/201211:30AM 12
07/18/201201:30PM 13
07/17/201203:30PM 22
This is a simple Linq-To-DataSet approach:
IEnumerable<DataRow> orderedRows = dataSet.Tables[0].AsEnumerable()
.OrderBy(r => r.Field<DateTime>("Date"));
Now you can use that as DataSource or enumerate it in a foreach. If you need to materialize it, you might want to create a new DataTable from it:
DataTable tblOrdered = orderedRows.CopyToDataTable();
You can create a data view from your data-set.
Then you can use the DataView.Sort Property to sort your data.
eg.
DataView myDataView = DT.DefaultView;
myDataView.Sort = "Date DESC";
Read more about Introduction to Filtering and Sorting in Datasets
Using Dataview you can sort your Datatable.
Just put your Datatable in Dataview
Look at the following example :
You have dtlog table which having two columns one is date and another one is detials.
you want to sort your datatable by date column.
DataTable dtlog = new DataTable();
dtlog.Columns.Add("date");
dtlog.Columns.Add("details");
1.create dataview and put your datatable in view
DataView dtview = new DataView(dtlog);
string sortstring = "date DESC"; // sorting in descending manner
dtview.Sort = sortstring;
2.Create another table where you can save your sorted dataview
DataTable dtsort =dtview.ToTable();
You can do this by a DataView. If your column which is holding datetime is a datetime column
DataView dv = DataTable.DefaultView;
dv.Sort = "DateTime-ColumnName ASC";
It will not work on string column holding datetime as string.
The DataView of a DataTable have a sort property please pass the column name to it
E.g.
dataSet1.Table[0].DefautlView.Sort = "ColumnName";
default sort is by ascending order
For more see link http://msdn.microsoft.com/en-us/library/system.data.dataview.sort(v=vs.100).aspx
I find my solucion is add more columns to Datatable where we can save each part of a DateTime:
Tabla.Columns.Add("year", typeof(DateTime));
Tabla.Columns.Add("month", typeof(DateTime));
Tabla.Columns.Add("day", typeof(DateTime));
then we can sort our datatable with a DataView:
DataView myDataView = DT.DefaultView;
case 1: ASC
myDataView.Sort = "year asc, month asc, day asc";
case 2: DESC
myDataView.Sort = "year desc, month desc, day desc";
Tabla = myDataViwe.toTable();
result is our datatable sorted for a dateTime
It worked for Me:
dataTableEmpSurvey.DefaultView.Sort = "SNO";
var dataTableSorted = dataTableEmpSurvey.DefaultView.ToTable();
https://www.codeproject.com/Questions/219205/How-To-Sort-Datatable-in-csharp-net

How to pass DataTable.Select() result to a new DataTable?

I have a DataTable named dt2 with data. I am calling its Select method to get some specific rows.
DataRow[] foundRows;
expression = "parent_id=1";
foundRows = dt2.Select(expression);
How can I pass the Select-method result to a new DataTable – say FilteredData?
You can use CopyToDataTable, available on IEnumerable<DataRow> types.
var filteredData = dt2.Select(expression).CopyToDataTable();
Just for clarity, the Select method returns an array of type DataRow. That's why we need to use CopyToDataTable(). Alex's answer is good. However, if the Select didn't return any rows, CopyToDataTable() will throw an InvalidOperationException.
So test that there is at least one DataRow before using the CopyToDataTable().
var filteredDataRows = dt2.Select(expression);
var filteredDataTable = new DataTable();
if(filteredDataRows.Length != 0)
filteredDataTable = filteredDataRows.CopyToDataTable();
Why not use a DataView instead?
DataView view = new DataView(dt2);
view.RowFilter = "parent_id = 1";
DataView will behave in very much the same way that a DataTable would with the added benefit that any change(s) to the underlying DataTable (dt2 in this case) would be automatically reflected in the DataView.

How to return a dataset from a dataset filtering value

I want to return a dataset filter from a static dataset.
Is it possible.?
You can filter Rows, by DataTable.Select function
private void GetRowsByFilter(){
DataTable myTable;
myTable = DataSet1.Tables["Orders"];
// Presuming the DataTable has a column named Date.
string strExpr;
strExpr = "Date > '1/1/00'";
DataRow[] foundRows;
// Use the Select method to find all rows matching the filter.
foundRows = myTable.Select(strExpr);
// Print column 0 of each returned row.
for(int i = 0; i < foundRows.Length; i ++){
Console.WriteLine(foundRows[i][0]);
}
}
Also You can get filtered DataSet by setting RowFilter property like this
ds.Tables[<table name>].DefaultView.RowFilter = "ProductId=5"
Look here for other ways to do filtering
But all of this methods does not create new DataSet with filtered data, if you need it , you should copy filtered rows manually I guess...

Categories