I have two DataTables : dt1 & dt2. dt1 contains one field, ID and dt2 contains two fields, ass_ID and Name.
I have to get the number of matched IDs from these two DataTables. How do I do this? Any easy way to compare them or anything to get the count of matched IDs (common IDs) in both of these tables?
var count = (from dr1 in dt.AsEnumerable()
from dr2 in dt2.AsEnumerable()
where dr1.Field<int>("ID") == dr2.Field<int>("ass_ID")
select dr1).Count();
Or
var count = (from dr1 in dt1.AsEnumerable()
join j in dt2.AsEnumerable() on dr1.Field<int>("ID") equals j.Field<int>("ass_ID")
select j).Count();
Try this:
string strExpression = string.Format("ID = '{0}'",dt2.Columns["ass_ID"]);
DafaultView dv = new DefaultView();
dv = dt1.DefaultView;
dv.RowFilter = strExpression;
//work with dv (DefaultView)
Related
Hi basically i wanted to group my datatable by the department column, i want to load the results back into another datatable through looping but it keeps giving me an error, im not sure how to group a datatable with linq and load it into another datatable other than looping
here is my code
DataTable data = new DataTable();
data.Columns.Add("Department");
var query1 = dtClone.AsEnumerable().GroupBy(row => row.Field<string>("department"));
if (query1.Any())
foreach(DataRow dr in query1)//here
{
DataRow newrow = data.Rows.Add();
newrow.SetField("Department", dr.Field<string>("department"));
}
foreach (DataRow row in data.Rows)
MessageBox.Show(row[0].ToString());
another linq query i tried
DataTable data = new DataTable();
data.Columns.Add("Department");
var query1 = from r in dtClone.AsEnumerable()
orderby r.Field<string>("department") ascending
group r by r.Field<string>("department") into r
select r;
if (query1.Any())
foreach(DataRow dr in query1)
{
DataRow newrow = data.Rows.Add();
newrow.SetField("Department", dr.Field<string>("department"));
}
No need to group data in case of getting distinct records (only one column).
var query1 = dtClone.AsEnumerable().Select(row => row.Field<string>("department")).Distinct();
ORDER BY
var query1 = dtClone.AsEnumerable().Select(row => row.Field<string>("department")).Distinct().OrderBy(s => s);
I have two data tables in my C# code, each with a single column called ID of type string.
I want to (inner) join the two tables on the ID column and get a count of the common rows. I don't need the IDs themselves, just the count of common IDs.
One of the tables may have duplicate IDs but the join must consider only distinct values so if there are two rows with ID=544 they should only count as one.
The two tables may have over a million rows each so performance is an issue. What would be the simplest and most efficient way to code this in C#?
It needs a simple inner join. If i understood you properly here i have given the solution. Try it and let me know if it solves your problem
using System;
using System.Linq;
using System.Data;
namespace JoinDatatablesConsoleApp
{
class Program
{
static void Main(string[] args)
{
DataTable dt1 = new DataTable();
dt1.Columns.Add("ID", typeof(string));
DataTable dt2 = new DataTable();
dt2.Columns.Add("ID", typeof(string));
for(int i=1;i<5;i++)
{
DataRow dr1 = dt1.NewRow();
dr1["ID"] = i + "A";
dt1.Rows.Add(dr1);
DataRow dr2 = dt2.NewRow();
dr2["ID"] = i + "A";
dt2.Rows.Add(dr2);
}
DataRow dr3 = dt2.NewRow();
dr3["ID"] = "7A";
dt2.Rows.Add(dr3);
var commonData = (from f1 in dt1.AsEnumerable()
join f2 in dt2.AsEnumerable()
on f1.Field<string>("ID")
equals f2.Field<string>("ID")
select f1.Field<string>("ID"))
.Distinct().ToList();
Console.WriteLine("Common Data : ");
foreach(var item in commonData)
{
Console.WriteLine(item);
}
Console.WriteLine("Common Data Count : " + commonData.Count);
Console.Read();
}
}
}
I have two datatables and I want to join them in several columns.here is my code
DataTable targetTable = dtl.Clone();
var dt2Columns = dt.Columns.OfType<DataColumn>().Select(dc =>
new DataColumn(dc.ColumnName, dc.DataType, dc.Expression, dc.ColumnMapping));
targetTable.Columns.AddRange(dt2Columns.ToArray());
var rowData =
from row1 in dtl.AsEnumerable()
join row2 in dt.AsEnumerable()
on row1.Field<string>("header")
equals row2.Field<string>("header")
where (row1.Field<string>("digitnumber") != "")
select row1.ItemArray.Concat(row2.ItemArray).ToArray();
foreach (object[] values in rowData)
targetTable.Rows.Add(values);
but it joins only on one condition.I want the code like below:
DataTable targetTable = dtl.Clone();
var dt2Columns = dt.Columns.OfType<DataColumn>().Select(dc =>
new DataColumn(dc.ColumnName, dc.DataType, dc.Expression, dc.ColumnMapping));
targetTable.Columns.AddRange(dt2Columns.ToArray());
var rowData =
from row1 in dtl.AsEnumerable()
join row2 in dt.AsEnumerable()
on row1.Field<string>("header") and row1.Field<string>("digitrow") and row1.Field<string> ("response")
equals row2.Field<string>("header") and row1.Field<string>("question") and and row1.Field<string> ("answer")
where (row1.Field<string>("digitnumber") != "")
select row1.ItemArray.Concat(row2.ItemArray).ToArray();
foreach (object[] values in rowData)
targetTable.Rows.Add(values);
but have some errors on multiple conditions.what's the solution?help me please.
from table1 in dt.TableA
join table2 in dt.Table2 on
new { table1.col1, table1.col2}
equals
new { table2.Column1,table2.Column2}
You can add multiple columns in the paranthesis in the same order for comparison.
is there any way to replace all occurrences of a value in a data table with another value from a different data table.for example I have two data table one has Itemid and another has itemid and item name.I need to replace item id in first data table with the item name from the second data table..Is there any possible way to replace all occurances at one go or should i go for the usual loop method and use Datatable.Select method.Please help.Thanks in advance.
What about this? (I realise it is a loop - but very compact and any built in method would loop anyway, just behind the scenes)
//Build first Test DT
DataTable dt1 = new DataTable();
dt1.Columns.Add("itemID", typeof(string));
//Build Second Test DT
DataTable dt2 = new DataTable();
dt2.Columns.Add("itemID", typeof(string));
dt2.Columns.Add("itemName", typeof(string));
//aad 3 DataRows to first DT - ID only
DataRow dt1_1 = dt1.NewRow();
dt1_1["itemID"] = "1";
DataRow dt1_2 = dt1.NewRow();
dt1_2["itemID"] = "2";
DataRow dt1_3 = dt1.NewRow();
dt1_3["itemID"] = "3";
dt1.Rows.Add(dt1_1);
dt1.Rows.Add(dt1_2);
dt1.Rows.Add(dt1_3);
//aad 3 DataRows to first DT - ID & Name
DataRow dt2_1 = dt2.NewRow();
dt2_1["itemID"] = "1";
dt2_1["itemName"] = "ItemOne";
DataRow dt2_2 = dt2.NewRow();
dt2_2["itemID"] = "2";
dt2_2["itemName"] = "ItemTwo";
DataRow dt2_3 = dt2.NewRow();
dt2_3["itemID"] = "3";
dt2_3["itemName"] = "ItemThree";
dt2.Rows.Add(dt2_1);
dt2.Rows.Add(dt2_2);
dt2.Rows.Add(dt2_3);
////////////////////////////////////////////////////////
//replacing code - quite comact - assumed itemId is PK//
////////////////////////////////////////////////////////
foreach (DataRow dr in dt1.Rows)
{
string strSelect = "[itemID] = '"+ dr["itemID"] +"'";
DataRow[] myRow = dt2.Select(strSelect);
if (myRow.Length == 1)
{
dr["itemID"] = myRow[0]["itemName"];
}
}
/////////////////////////////////////////////////////////////////
//dt1 now has itemOne, itemTwo and itemThree instead of 1, 2, 3//
/////////////////////////////////////////////////////////////////
With MySQL I would try:
UPDATE table1 t1, table2 t2
SET t1.itemid = t2.itemname
WHERE t1.itemid = t2.itemid
With MS-SQL I would try
UPDATE t1
SET t1.itemid = t2.itemname
FROM table1 t1 INNER JOIN table2 t2
ON t1.itemid = t2.itemid
have a Dataset Ds1 and dataset Ds2 , DS1 has Product_ID, product information and ds2 has Product_ID, product_type.
for the matching product_id, I want to add the Product_tye column from ds2 to ds1 .
Note: Product_id is not primary key in ds 1, the result set has many products with same product_id. In ds 2, product_id is unique. also, those datatbles are from two different databases on different servers and has different credentials , so cant use sql joins.
I tried to use linq to acheive this, but not getting the desired output, please correct me if i am mising something .
DataTable dt1 = new DataTable();
DataTable dt2 = new DataTable();
//After both the datatble has values, using linq to add datatble columsn,
DataTable result = (from t1 in dt1.AsEnumerable()
join t2 in dt2.AsEnumerable() on t1.Field<string>("productID") equals t2.Field<string>("productID")
select t1).CopyToDataTable();
Selecting both tables
DataTable result = (from t1 in dt1.AsEnumerable()
join t2 in dt2.AsEnumerable() on t1.Field<string>("productID")
equals t2.Field<string>("productID")
select new {t1,t2}
).CopyToDataTable();
OR Selecting selected columns
DataTable result = (from t1 in dt1.AsEnumerable()
join t2 in dt2.AsEnumerable() on t1.Field<string>("productID")
equals t2.Field<string>("productID")
select new {
productId = t1.productID,
col2 = t1.col2,...,
productType = t2.pruductType
).CopyToDataTable();
NOTE: I think productID type should be int type so replace string with int in that case
I have just created you a simple example, what you have to do is to change column names from my code, with your own:
DataTable table1 = new DataTable();
DataTable table2 = new DataTable();
table1.Columns.Add("id", typeof(int));
table1.Columns.Add("name", typeof(string));
table2.Columns.Add("id", typeof(int));
table2.Columns.Add("age", typeof(int));
table1.Rows.Add(1, "mitja");
table1.Rows.Add(2, "sandra");
table1.Rows.Add(3, "nataška");
table2.Rows.Add(1, 31);
table2.Rows.Add(3, 24);
table2.Rows.Add(4, 46);
DataTable targetTable = table1.Clone();
//create new column
targetTable.Columns.Add("age");
var results = from t1 in table1.AsEnumerable()
join t2 in table2.AsEnumerable() on t1.Field<int>("id") equals t2.Field<int>("id")
select new
{
ID = (int)t1["id"],
NAME = (string)t1["name"],
AGE = (int)t2["age"]
};
foreach (var item in results)
targetTable.Rows.Add(item.ID, item.NAME, item.AGE);
Be careful on defining type of variables (int, string, ...) in any case!!!
Hope it helps.