C#: retrieve the first n records from a DataTable - c#

I have a DataTable that contains 2000 records.
How would you retrieve the first 100 records in the DataTable?

If it implements IEnumerable<T>:
var first100 = table.Take(100);
If the type in question only implements IEnumerable, you can use the Cast extention method:
var first100 = table.Cast<Foo>().Take(100);

This works for DB2.
select * from table
fetch first 100 rows only;

and for mysql: select * from table limit 100

You could use something like this, but restrict the foreach loop to 100 records.

And to make the list full, here is the statement for MS SQL:
Select top 5 * from MyTable2
And some other methods with MS SQL can be found here.

To get a list of the top n records in C# using the 2.0 framework:
DataTable dt = new DataTable();
var myRows = new List<DataRow>();
//no sorting specified; take straight from the top.
for (int i = 0; i < 100; i++)
{
myRows.Add(dt.Rows[i]);
}

Related

take top 10 or 20 rows from dynamic datatable

I have 100 records in my Datable says to be in
DataTable dt=new DataTable();
dt have 100 of records say column name as sub_id(contain int datatype) and subheadername(contain nvarchar(150)) , I want top 20 records from this dt in ascending order
I am putting code as
//dtlcategories.DataSource = dt.AsEnumerable().OrderBy(x => x["subheadername"]).Take(20).ToList();
dtlcategories.DataSource = dt.Rows.Cast<DataRow>().OrderBy(x => x["subheadername"]).Take(20).ToList();
dtlcategories.DataBind();
Here dtlcategories is Datalist but on running error is coming as 'System.Data.DataRow' does not contain a property with the name 'subheadername'.
ANSWER IS SOLVED
dtlcategories.DataSource = dt.Rows.Cast<DataRow>().OrderBy(x => x["subheadername"]).Take(20).copytodatatable();
dtlcategories.DataBind();
There's a couple different ways you can do this using LINQ. These will both return the same results.
dt.AsEnumerable().OrderBy(x => x["subheadername"]).Take(20);
dt.Rows.Cast<DataRow>().OrderBy(x => x["subheadername"]).Take(20);
If you're going to use the result as the source of data for another control, you may need to call .ToList() after .Take(x).
Edit:
I changed the column name based on your edit. If you want to sort by id instead (you didn't specify), just replace "subheadername" with "sub_id".
This query fetches top 20 records from db and then orders them by the sub_id column.
var topTwenty = dt.AsEnumerable().Take(20).OrderBy(r => r.Field<int>("sub_id"));
dt.AsEnumerable().OrderBy(row => row["sub_id"]).Take(20);
This will return you IEnumerable. Now iterate through the IEnumerable and add them to another data table. Now your final data table is ready!!
this code orders data according to date and takes first 100 row.
var table = new DataTable();
var t = table.AsEnumerable();
var result = t.OrderByDescending(f => f.Field<DateTime>(new DataColumn("Date"))).Take(100);
Update:
var table = new DataTable();
var t = table.AsEnumerable();
var result = t.OrderBy(f => f.Field<String>(new DataColumn("subheadername"))).Take(20)
A possible solution:
DataRow[] rows = dt.Select("sub_id< 100 ");

Get sum from a DataColumn values in C#

I have a table in a dataadapter. I want to get the count and sum of a specific column of it. How is that possible?
This is the code for reach to the column, what after that?
DataColumn buy_count = myDataSet.Tables["all_saled"].Columns["how_much_buy"]
I know that we have sum, count,... in SQL, but how can I do it in C#?
You can use LINQ to DataSets
var sales = myDataSet.Tables["all_saled"].AsEnumerable();
var buy_total = sales.Sum(datarow => datarow.Field<int>("how_much_buy"));
Check the LINQ to DataSets 101 Samples
P.S. might need the System.Data.DataSetExtensions assembly referenced.
Use the DataTable.Compute method:
int total = (int)myDataSet.Tables["all_saled"].Compute("SUM(how_much_buy)", null);

Querying inside a Dataset C#

I have an ADO.NET dataset which is set by a certain query,
say
SELECT ID,USER,PRODUCT,COUNT FROM PRODUCTION
Without using a where clause I need to derive some results from the dataset. Say I want to get the User and Product count of the user who has the maximum product count. (And I want to do it by using the existing dataset. I can't derive this from dataset.)
Any idea of a way to query inside the dataset? Since there are Datatables my thought was there is some way to query it.
Traditional SQL queries cannot be applied to the DataSet. The following is possible, however:
Filter rows using DataTable.Select. See here for detailed information about expressions in DataTables.
Calculate totals etc. using DataTable.Compute.
If these two don't do the trick, there's always LINQ.
Quick-and-dirty LINQ example: (which doesn't return a DataTable, but a list containing an anonymous type):
var joinedResult = dataTable1
// filtering:
.Select("MyColumn = 'value'")
// joining tables:
.Join(
dataTable2.AsEnumerable(),
row => row.Field<long>("PrimaryKeyField"),
row => row.Field<long?>("ForeignKeyField"),
// selecting a custom result:
(row1, row2) => new { AnotherColumn = row1.Field<string>("AnotherColumn") });
AsEnumerable converts a DataTable into an IEnumerable on which LINQ queries can be performed. If you are new to LINQ, check out this introduction.
Yes, you can use DataTable.Select method.
DataTable table = DataSet1.Tables["Orders"];
// Presuming the DataTable has a column named Date.
string expression;
expression = "Date > #1/1/00#";
DataRow[] foundRows;
// Use the Select method to find all rows matching the filter.
foundRows = table.Select(expression);
// Print column 0 of each returned row.
for(int i = 0; i < foundRows.Length; i ++)
{
Console.WriteLine(foundRows[i][0]);
}
Also see this link.
You can do cross-table queries of a Dataset object using LINQ to DataSet:
msdn.microsoft.com/en-us/library/bb386969.aspx

C# DataTable LINQ & GROUP BY

I have a DataTable with 20 columns (I only need 3 of them.) I need to perform the following query on it and then save the results as an array. I've done some searching, but I can't figure out how to perform the mathematical operation. I know LINQ should be used, but I'm not getting anywhere. Any help is greatly appreciated!
SELECT DISTINCT columnZ, (columnX + columnY) / 2 FROM DataTable
*EDIT - corrected SQL statement
Answering your last comment (I suggest you update the question):
var result =
(from row in dataTable.AsEnumerable()
let average = ((double)row["columnX"] + (double)row["columnY"])/2
select new
{
ColumnZ = (string)row["columnZ"],
Average = average
}).Distinct();
Use your actual data types.

Data table select top 5 rows

Hi is there any way to select top 5 rows from a data table without iteration?
I think, You can use LINQ:
datatable.AsEnumerable().Take(5);
Using 2 of the above posts, the following works for me:
foreach (DataRow _dr in DataSet.Tables[<tblname>].Select("", "Timestamp DESC").AsEnumerable().OfType<DataRow>().Take(5))
So now you can normally filter if you want, order if you want and then get only the amount of records that you want and then iterate through them whether it is 1 or 100.
Hope that helps someone.
This is what worked for me:
datatable.Rows.Cast<System.Data.DataRow>().Take(5);
This works for my needs.
public static DataTable TopRows(this DataTable dTable, int rowCount)
{
DataTable dtNew = dTable.Clone();
dtNew.BeginLoadData();
if (rowCount > dTable.Rows.Count) { rowCount = dTable.Rows.Count; }
for (int i = 0; i < rowCount;i++)
{
DataRow drNew = dtNew.NewRow();
drNew.ItemArray = dTable.Rows[i].ItemArray;
dtNew.Rows.Add(drNew);
}
dtNew.EndLoadData();
return dtNew;
}
to use it you then do this:
dataTable.TopRows(5);
If you use a LINQ statement, you could use the Take() method.
This post may be of some assistance as well.
EDIT
As you are using VS2005, use the SELECT() method in the datatable like so:
DataRow[] rows = datatable.Select('TOP 5');

Categories

Resources