Get Count of DataSet.Tables rows based on criteria - c#

The code below is returning a value of 0 every time. I am trying to filter a datatable and get the number of rows. To illustrate the example here, I am setting the criteria as the value 250 to be looked for in my ID column in Table2.
How can I fix it?
var count = (from row in MyDatabaseDataSet.Tables["Table2"].AsEnumerable() where string.Equals(row["ID"].ToString(), 250)) select row).Count();
MessageBox.Show(Convert.ToString(count));

Try that one:
var count = (from row in MyDatabaseDataSet.Tables["Table2"].AsEnumerable()
where row.Field<int>("ID") == 250
select row).Count();

With method syntax:
int rowCount = MyDatabaseDataSet.Tables["Table2"].AsEnumerable()
.Count(r => r.Field<int>("ID") == 250);

Ok emmmmmmm well this is... awkward... I absolutely forgot to fill the dataset with the second table before calling the code. Here's what I had forgotten:
// TODO: This line of code loads data into the 'showsDatabaseDataSet.AllEpisodes' table. You can move, or remove it, as needed.
this.MyTableAdapter.Fill(this.MyDatabaseDataSet.Table2);
It is now working thanks guys!

Related

Linq SELECT query not returning first row of DataTable

This should be a real simple operation but for some reason it's not working as expected. I'm trying to copy all the rows out of a DataTable "mainDatatable" that have their Export Cell = 'True'
Here's my code:
DataTable table = model.getData.Tables["mainDataTable"].Clone();
var rows = model.getData.Tables["mainDatatable"].Select("Export = 'True'");
foreach (var row in rows)
{
table.ImportRow(row);
}
Now, When i run this it always gets all rows with Export = "True", all but the very first row that is in the DataTable... Am i doing something wrong??
I cannot see any reason why you are not getting this if your table-data is all correct. Please check this:-
Is your True actually a string? If Yes, please check the data again. There might be a *space * with the 'true' in the first row.
I'm not that familiar with DataTable but in Linq an query isn't build with Select but with Where.
So I would try something like:
var rows = model.getData.Tables["mainDatatable"].AsEnumerable().Where(x=>x.Field<string>("Export").Equals("true"));
or - if its a boolean
var rows = model.getData.Tables["mainDatatable"].AsEnumerable().Where(x=>x.Field<bool>("Export"));

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 ");

Retrieve specific datarow in C# Datatable

I have a datatable in C# called "table" that looks like the following:.
ID Value
10 A
20 B
30 C
(It really has about 1200 rows, but I tried to simplify it)
My goal is to be able to print specific rows in this datatable. For example, if I would like to print the second row (row index 1) I would use the following:
Response.Write(table.Rows[1]["Value"].ToString());
This prints out the value "B" which is what I want, but is there a way to use the "ID" column to print that specific value instead of using the row index of 1. I would like to be able to link ID 10 and Value B together somehow.
If ID is defined as the primary key, this should look up B by its ID key:
Response.Write(table.Rows.Find(20).["Value"].ToString());
If ID isn't setup as a PK (or you want to query another field), you could use a Linq query
var chosenRow = (from row in table.AsEnumerable()
where row.Field<int>("ID") == 10
select row).First();
chosenRow is the first DataRow object that meets the criteria set in the where clause. So you could just:
Response.Write(chosenRow["Value"].ToString());
you can loop trough your datatable using for each, and when the ID equals 10, then you do what you want
would be something like this:
for each row as datarow in datatable.rows
if row.Items["ID"] = 10 Then
//do something
end if

Last Row of Filtered DataView in C#

I have a DataView which was filtered to contain only those records I need. On top of that I would like to get the first record in the Dataview.
//appDV contains a bunch of records with different LOAN_STATUS. Here I'm filtering it by Approved
appDV.RowFilter = "LOAN_STATUS = 'Approved'";
appDV.Sort = "CREATE_TIME DESC";
// If more than one record, take the 1st record
appuser = new AppUserVO();
appuser.APPUSER_ID = Convert.ToInt32(appDV.Table.Rows[0]["APPUSER_ID"].ToString());
appuser.BankLenderId = appDV.Table.Rows[0]["BANK_LENDERID"].ToString().Trim();
AppList.Add(appuser);
return AppList;
The code above is not returning the correct Row... because it is returning me the Row of the DataView BEFORE the filter was applied.
What am I doing wrong?
I don't think you need the .Table. call and instead should use
appDV.Rows[0]["APPUSER_ID"].ToString();
After you set sort expression and row filter, you have to call DataView.ToTable()
To get a column value from the first row :
string columnVal= appDV.ToTable().Rows[0]["COLUMN_NAME"].ToString();
You must use the .ToTable() first to convert you retrieved values in the DataView to a DataTable.

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.

Categories

Resources