I have to perform the aggregate function on the DataTable like Datatable.Compute but compute return the object i want to perform the aggregate function on the datatable and get the datarow .
_summaryTable.Compute("min(FareAdult)", whereClause
+ "AirlineDisplayName='"
+ Convert.ToString(airline["AirlineDisplayName"])
+ "' and ( Stops=0) ");
but above code will only return the min(FareAdult) but i want to select the two column based on the above condition from datatable.
How can i do it through Linq
I have to select min(FareAdult) and the TotelPrice value of same row
use Select instead compute
_summaryTable.Select("FilterationExpression");
DataRow[] dr = _summaryTable.Select("min(FareAdult),AirlineDisplayName='" + Convert.ToString(airline["AirlineDisplayName"]) + "' and ( Stops=0) ");
Here is a LINQ method. This is pseudocode since I don't know the typing of your row, and I haven't been able to test it, but the idea is the same. Use LINQ to select the rows that match your criteria, order by the FareAdult and then select the first (minimum).
var minResult = (from row in _summaryTable.Rows
where row.AirlineDisplayName == airline["AirlineDisplayName"] && row.Stops == 0
orderby row.FareAdult
select row).FirstOrDefault();
private void CalcColumns()
{
DataTable table = new DataTable ();
//enter code here
// Create the first column.
DataColumn priceColumn = new DataColumn();
priceColumn.DataType = System.Type.GetType("System.Decimal");
priceColumn.ColumnName = "price";
priceColumn.DefaultValue = 50;
// Create the second, calculated, column.
DataColumn taxColumn = new DataColumn();
taxColumn.DataType = System.Type.GetType("System.Decimal");
taxColumn.ColumnName = "tax";
taxColumn.Expression = "price * 0.0862";
// Create third column.
DataColumn totalColumn = new DataColumn();
totalColumn.DataType = System.Type.GetType("System.Decimal");
totalColumn.ColumnName = "total";
totalColumn.Expression = "price + tax";
// Add columns to DataTable.
table.Columns.Add(priceColumn);
table.Columns.Add(taxColumn);
table.Columns.Add(totalColumn);
DataRow row = table.NewRow();
table.Rows.Add(row);
DataView view = new DataView(table);
dataGrid1.DataSource = view;
}
Related
I need to get each value from mysql table by using DataTable without using a loop. Here I have two DataTables, I want to increment dtfilmsngtemp and need to get values, i.e if dtsnglyric have id=2, Then I need to have get id=2 in dtfilmsngtemp, So in general I need to get he same 'id's' from two DataTables. First of all row id is 1 in dtsnglyric and dtfilmsngtemp, But dtsnglyric is incremented to 2, According to my requirement dtfilmsngtemp is also need to become 2. How it is possible?
DataTable dtsnglyric = GetAllsnglyrctmp();
DataTable dtfilmsngtemp = GetAllfilmsngtemp();
foreach (DataRow drow1 in dtsnglyric.Rows)
{
string lyrsct = drow1["lyricist"].ToString();
string sngrs = drow1["singers"].ToString();
foreach (DataRow drow in dtfilmsngtemp.Rows)
{
string lid = drow["lyric_id"].ToString();
string fid = drow["film_id"].ToString();
}
}
Try this
protected void Page_Load(object sender, EventArgs e)
{
// Check
if (!IsPostBack)
{
// Variable
DataTable dt1 = new DataTable();
DataTable dt2 = new DataTable();
DataRow[] dr1 = null;
DataRow[] dr2 = null;
string value1 = string.Empty;
string value2 = string.Empty;
dt1.Columns.Add("A");
dt1.Columns.Add("B");
dt2.Columns.Add("A");
dt2.Columns.Add("B");
// Add to DataTable
for (int i = 0; i < 10; i++)
{
dt1.Rows.Add(i.ToString(), (i + 1).ToString());
dt2.Rows.Add(i.ToString(), (i + 2).ToString());
}
// Find By Select Example i want to take dt1 Column A = 2 and dt2 Column A = 9
dr1 = dt1.Select("A=2"); // Select statement >>> Column = Value
dr2 = dt2.Select("A=9");
// Check & Get B Value
if (dr1 != null && dr1.Length == 1) value1 = dr1[0]["B"] + "";
if (dr2 != null && dr2.Length == 1) value2 = dr2[0]["B"] + "";
Response.Write(value1 + ":" + value2);
}
}
I think you need an inner join operation. Can't you do it in the SQL query? DataTable doesn't support that, but you can do it with LINQ. However, note that it will take O(n^2) time and shouldn't be used for big tables:
var results = from table1 in dtsnglyric.AsEnumerable()
join table2 in dtfilmsngtemp.AsEnumerable() on (int)table1["lyricist"] equals (int)table2["lyric_id"]
select new
{
lyricist= (int)table1["lyricist"],
lyric_id= (int)table2["lyric_id"],
film_id= (int)table2["film_id"],
singers = (int)table1["singers"]
};
I have the following DataTable records :-
I want to display the Rows for which HeaderPrintOrder Column don't have 0 as value. And in PDF Cell I have to print FieldName : Amount by iterating to the records with above given condition.
I am trying the below code, gives me error Cannot interpret token '!'. What is correct way to do this?
var datatable = new DataTable();
datatable.Load(reader);
DataRow[] HeadingFields = datatable.Select("HeaderPrintOrder != 0");
foreach (var item in HeadingFields)
{
cellHead = new PdfPCell(new Phrase(HeadingFields[item]["FieldName"].ToString() + " : " + HeadingFields[item]["Amount"].ToString(), fntTableFont));
cellHead.Colspan = 3;
MainTable.AddCell(cellHead);
}
With LINQ it's easy:
var filtered = datatable.AsEnumerable()
.Where(row => row.Field<int>("HeaderPrintOrder") != 0);
foreach(DataRow row in filtered)
{
// ....
}
With DataTable.Select you have to use <> instead of !=:
DataRow[] HeadingFields = datatable.Select("HeaderPrintOrder <> 0");
<> is supported whereas != is not. You can see that here:
http://msdn.microsoft.com/en-us/library/system.data.datacolumn.expression%28v=vs.110%29.aspx
The != operator is not supported by the RowFilter syntax.
Try:
DataRow[] HeadingFields = datatable.Select("NOT (HeaderPrintOrder = 0)");
Try with Linq:
var HeadingFields= from row in datatable .AsEnumerable()
where row.Field<int>("HeaderPrintOrder") <> (int)(0)
select row;
My Datatable 1 (dtOutput) Format (termid,faultid,faultdesc,faulttime,devicetype)
My Datatable 2 (dtOpenEvent) Format (termid,faultid)
I want to retrieve those values which are present in Datatable 2 but not in Datatable 1...based on two columns (termid,faultid) no table have primary keys.
I Searched on net and find code which return diff between two data table...
Now how can i retrieve column values from it ? either in another data table or in string variable
Code :-
DataTable dtOpenEvent;
dtOpenEvent = Generix.getOpenEvents(ref Connection);
DataTable dtOutput;
dtOutput = Generix.getFeedData(ref Connection);
var matched = from table1 in dtOpenEvent.AsEnumerable()
join table2 in dtOutput.AsEnumerable() on table1.Field<string>("ATM") equals table2.Field<string>("termid")
where table1.Field<int>("Event") == table2.Field<int>("faultid")
select table1;
var missing = from table1 in dtOpenEvent.AsEnumerable()
where !matched.Contains(table1)
select table1;
you can remove all of the columns in dt1 and then do except.
like this:
var diff =dt2.AsEnumerable().Except(dt1.AsEnumerable(), DataRowComparer.Default);
full example:
DataTable dt1 = new DataTable();
DataTable dt2 = new DataTable();
dt1.Columns.Add("termid", typeof(Int32));
dt1.Columns.Add("faultid", typeof(Int32));
dt1.Columns.Add("faultdesc");
dt2.Columns.Add("termid", typeof(Int32));
dt2.Columns.Add("faultid", typeof(Int32));
dt1.Rows.Add(1,2,"desc");
dt1.Rows.Add(3, 4, "desc");
dt1.Rows.Add(5, 6, "desc");
dt2.Rows.Add(1, 2);
dt2.Rows.Add(3, 4);
dt2.Rows.Add(7, 8);
dt1.Columns.Remove("faultdesc");
var diff =dt2.AsEnumerable().Except(dt1.AsEnumerable(), DataRowComparer.Default);
foreach (var row in diff)
{
Console.WriteLine(row["termid"] + " " + row["faultid"]); //prints 7 8
}
or instead of removing columns you can select them through linq or dataview like this:
var view = new DataView(dt1);
DataTable dt3 = view.ToTable(true, "termid", "faultid");
modified example:
DataTable dt1 = new DataTable();
DataTable dt2 = new DataTable();
dt1.Columns.Add("termid", typeof(Int32));
dt1.Columns.Add("faultid", typeof(Int32));
dt1.Columns.Add("faultdesc");
dt2.Columns.Add("termid", typeof(Int32));
dt2.Columns.Add("faultid", typeof(Int32));
dt1.Rows.Add(1,2,"desc");
dt1.Rows.Add(3, 4, "desc");
dt1.Rows.Add(5, 6, "desc");
dt2.Rows.Add(1, 2);
dt2.Rows.Add(3, 4);
dt2.Rows.Add(7, 8);
var view = new DataView(dt1);
DataTable dt3 = view.ToTable(true, "termid", "faultid");
var diff =dt2.AsEnumerable().Except(dt3.AsEnumerable(), DataRowComparer.Default);
foreach (var row in diff)
{
Console.WriteLine(row["termid"] + " " + row["faultid"]);
}
As you said : I want to retrieve those values which are present in Datatable 2
but not in Datatable 1...based on two columns `(termid,faultid)`
Translation according to the context of question : You have two tables dtOutput and dtOpenEvent. You want to get values of dtOutput in a third table such that no row of third table has same value with first two cells of any row of dtOpenEvent. Then here it is
DataTable dt3 = new DataTable();
dt3.Columns.Add("termid");
dt3.Columns.Add("faultid");
int nr = 0;
for (int i = 0; i < dtOutput.Rows.Count; i++)
{
bool found = false;
for (int j = 0; j < dtOpenEvent.Rows.Count; j++)
{
if (dtOutput.Rows[i][0] == dtOpenEvent.Rows[j][0]
&& dtOutput.Rows[i][1] == dtOpenEvent.Rows[j][1])
{
found = true;
break;
}
}
if (!found)
{
dt3.Rows.Add(dt3.NewRow());
dt3.Rows[nr][0] = dtOutput.Rows[i][0];
dt3.Rows[nr][1] = dtOutput.Rows[i][1];
nr++;
}
}
I have created and returned datatable, this table has 10 columns. Now i want to filter from this table based on some dynamic search parameters. How to do this? any idea would be timely help.
// This function will create and return the source table.
var DisplayTable = CreateQueryTable();
Here I want to do dynamic search like If col1=MyName and Col2=MyCity
ResultGrid.DataSource = DisplayTable;
ResultGrid.DataBind();
Panel1.Controls.Add(ResultGrid);
You can do this in these way,
1.Creating DataView Like
var dv = dataTable.DefaultView;
dv.RowFilter = "col1='MyName' and Col2='MyCity'"; // if MyName and MyCity are literal string.
or
dv.RowFilter = "col1='"+MyName+"' and Col2 ='"+ MyCity +"'";// if MyName and MyCity are string variable.
2.With DataTable Select Method, It will return array of DataRow
var rows = dataTable.Select("col1='MyName' and Col2='MyCity'"); //if string literal
or
var rows = dataTable.Select("col1='"+MyName+"' and Col2='"+MyCity+"'"); // if string variable
3.By Linq
var filterdData = from row in dataTable.AsEnumerable()
where row.Field<string>("col1") == "MyName"
&& row.Field<string>("col2") == "MyCity"
select row;
you create DataView of your datatable and use Filter
// Create a DataView
DataView dv = new DataView(yourDataTable);
dv.RowFilter = "col1='MyName' and Col2='MyCity'";
//Bind your grid with DataView
You can also use select method on your table
DataRow[] foundRows;
foundRows = yourDataTable.Select("col1='MyName' and Col2='MyCity'");
You can also use Linq To DataTable
var results = from myRow in yourDataTable.AsEnumerable()
where myRow.Field<string>("col1") == Myname &&
myRow.Field<string>("Col2") == MyCity
select myRow;
i have a DataTable that has a column ("Profit"). What i want is to get the Sum of all the values in this table. I tried to do this in the following manner...
DataTable dsTemp = new DataTable();
dsTemp.Columns.Add("Profit");
DataRow dr = null;
dr = dsTemp.NewRow();
dr["Profit"] = 100;
dsTemp.Rows.Add(dr);
dr = dsTemp.NewRow();
dr["Profit"] = 200;
dsTemp.Rows.Add(dr);
DataView dvTotal = dsTemp.DefaultView;
dvTotal.RowFilter = " SUM ( Profit ) ";
DataTable dt = dvTotal.ToTable();
But i get an error while applying the filter...
how can i get the Sum of the Profit column in a variable
thank you...
Set the datacolumn to a numeric type (int, decimal, whatever):
DataColumn col = new DataColumn("Profit", typeof(int));
dsTemp.Columns.Add(col);
Use Compute:
int total = dsTemp.Compute("Sum(Profit)", "");
Note that aggregation is not a type of filter, which is the main problem with the approach you are tyring.
I used the DataTable's Compute method as suggested, and it works fine. I apply the same filtering as I use for the DataView (which is used to display the sorted and filtered data in the data grid) together with an aggregate function.
string SingleVocheridSale ="1";
DataView view = new DataView(dt);
view.RowFilter = string.Format("VOCHID='" + SingleVocheridSale + "'");
dataGridview1.DataSource = view;
object sumObject;
sumObject = dt.Compute("Sum(NETAMT)", view.RowFilter);
lable1.Text = sumObject.ToString();