How to merge two datatables, which having different schema? - c#

I have two Datatables shown in below
Table 1
-------------------------
ID | Name
--------------------------
1 | JOHN
2 | GEORGE
3 | RAGU
--------------------------
Table 2
----------
ID | AGE
----------
1 | 23
2 | 23
3 | 22
----------
I just want the result as like this..
Result
-------------------------
ID | Name | AGE
--------------------------
1 | JOHN | 23
2 | GEORGE | 23
3 | RAGU | 22
--------------------------
Thanks..

you can check this out:
static void Main(string[] args)
{
Program p = new Program();
DataTable dt1= p.Get1();
DataTable dt2 = p.Get2();
DataTable dt3 = p.Get3(dt1, dt2);
}
public DataTable Get1()
{
DataTable dt1 = new DataTable();
dt1.Columns.Add("ID");
dt1.Columns.Add("Name");
dt1.Rows.Add("1", "JOHN");
dt1.Rows.Add("2", "GEORGE");
dt1.Rows.Add("3", "RAGU");
return dt1;
}
public DataTable Get2()
{
DataTable dt2 = new DataTable();
dt2.Columns.Add("AGE");
dt2.Rows.Add("23");
dt2.Rows.Add("23");
dt2.Rows.Add("22");
return dt2;
}
public DataTable Get3(DataTable dt1,DataTable dt2)
{
dt1.Columns.Add("Age");
for (int i = 0; i < dt1.Rows.Count; i++)
{
dt1.Rows[i]["Age"] = dt2.Rows[i]["Age"];
}
return dt1;
}

I assume that this is what you might be looking for
INSERT INTO Result (ID, Name, Age)
SELECT T1.ID, T1.Name, T2.Age
FROM
Table1 AS T1
INNER JOIN
Table2 AS T2
ON
T1.ID = T2.ID
ORDER BY
T1.ID

Have you heard about INNER JOIN?
Basically, what you want to do is:
SELECT Persons.ID, Persons.Name, Ages.Age
FROM Persons INNER JOIN Ages ON Persons.ID = Ages.ID
Now you can insert that into another table if you want.

Related

Merge two datatables in C#?

I have two datatables ..
DataTable dtTemp= new DataTable();
dtTemp.Columns.AddRange(new[]
{
new DataColumn("segment_id", typeof(int)),
new DataColumn("seg_description")
});
DataTable dtTemp2 = new DataTable();
dtTemp2.Columns.Add("set_id",typeof(int));
Now lets have some rows into first table..
segment_id|seg_description
------ |---------------
1 | desc..
2 | desc2..
3 | desc3..
Now lets have some data into second table..
set_id
--------
1
--------
2
Now, I want marge this two tables to get below output
set_id | segment_id |seg_description
--------| ---------- | --------------
1 | 1 | desc..
1 | 2 | desc2..
1 | 3 | desc3..
2 | 1 | desc..
2 | 2 | desc2..
2 | 3 | desc3..
How can I do this?using Merge() can I achieve this?
So you want to "cross-join" the tables by building a cartesian product of all rows? Of course there is no builtin way, you can use this method:
public static DataTable CrossJoinTables(DataTable t1, DataTable t2)
{
if (t1 == null || t2 == null)
throw new ArgumentNullException("t1 or t2", "Both tables must not be null");
DataTable t3 = t1.Clone(); // first add columns from table1
foreach (DataColumn col in t2.Columns)
{
string newColumnName = col.ColumnName;
int colNum = 1;
while (t3.Columns.Contains(newColumnName))
{
newColumnName = string.Format("{0}_{1}", col.ColumnName, ++colNum);
}
t3.Columns.Add(newColumnName, col.DataType);
}
IEnumerable<object[]> crossJoin =
from r1 in t1.AsEnumerable()
from r2 in t2.AsEnumerable()
select r1.ItemArray.Concat(r2.ItemArray).ToArray();
foreach(object[] allFields in crossJoin)
{
t3.Rows.Add(allFields);
}
return t3;
}
Usage:
DataTable tblresult = CrossJoinTables(dtTemp2, dtTemp); // swapped order because you want columns from dtTemp2 first
To do this you need to use the CROSS JOIN operation.
Select * Table1 CROSS JOIN Table2
It literally gives you the product of the two tables : Every row in A joined to every row in B. if A has 100 rows and B has 100 rows, the Cross Join has 10,000 rows.
How about this:
var dt1 = dtTemp1.AsEnumerable();
var dt2 = dtTemp2.AsEnumerable();
var q = from x in dt1
from y in dt2
select new { set_id = (int)y["set_id"], segment_id = (int)x["segment_id"], seg_description = (string)x["seg_description"] };

Join Tables in LINQ

I have a table with following format:
---------------------------------------------
|name | date | timeTable |clockIn|clockOut|
---------------------------------------------
|jhon |01/02/15| Mornning | 08:29 |______ |
---------------------------------------------
|jhon |01/02/15| Afternoon |_______| 04:31 |
---------------------------------------------
|Harry|01/02/15| Mornning | 08:23 |_______ |
---------------------------------------------
|Harry|01/02/15| Afternoon |_______| 04:29 |
---------------------------------------------
From this above table, my desired format is:
---------------------------------------------
|name | date | clockIn|clockOut|
---------------------------------------------
|jhon |01/02/15| 08:29 | 04:31 |
---------------------------------------------
|Harry|01/02/15| 08:23 | 04:29 |
---------------------------------------------
My working is as follows:
Controller
var t1 = (from a in hc.attendanceLogs
where (a.timeTable == "Morning")
select new
{
name = a.name,
date = a.date,
timeTable = a.timeTable,
clockIn = a.clockIn
}).ToList();
var t2 = (from a in hc.attendanceLogs
where a.timeTable == "Afternoon"
select new
{
date = a.date,
clockOut = a.clockOut
}).ToList();
DataTable finalTable = new DataTable();
finalTable.Columns.Add("name", typeof(string));
finalTable.Columns.Add("date", typeof(string));
finalTable.Columns.Add("clockIn", typeof(string));
finalTable.Columns.Add("clockOut", typeof(string));
var t3 = from a in t1
join d in t2
on
a.date equals d.date
select
finalTable.LoadDataRow(
new object[]
{ a.name, a.date, a.clockIn, d.clockOut },
false);
ViewBag.Data = finalTable;
What I'm trying to do is, cut first 4 columns of the initial table hc.attendanceLogs and popluate them in variable t1. Then I take the last column of the initial table hc.attendanceLogs and popluate it in variable t2. Finally, join t1 with t2 into finalTable, where date in t1 is equal to date in t2.
Problem is ViewBag.Data is coming as empty when I try to display finalTable in a View.
Any ideas where I'm going wrong?
I think this is because you are not actually evaluating or iterating through t3.
Try adding a .ToList() and the end of the var t3 == ... line.

LINQ sum of one column and insert to another table C#

i have two tables suck as the one below i wanna know how to sum "calorie" column based on name from table 1 and then insert the value to table 2
table1(PK->ID(int),Name(nvarchar),amount(int),calorie(int))
table2(pk->ID(int),name(nvarchar),totalcalorie(int))
+-------+--------+----------+--------------+
| int | name | amount | calorie |
+-------+--------+----------+--------------+
| 1 | a | 10 | 20 |
| 2 | b | 5 | 20 |
| 2 | b | 10 | 10 |
| 1 | a | 10 | 10 |
| 2 | b | 15 | 35 |
| 3 | c | 20 | 15 |
+-------+--------+----------+--------------+
something like this is my first table now imagine same kinda table for table2
only this time something like :
1-------a--------30
2-------b--------65
3-------c--------15
is this possible at all? what i wrote till now and doesn't work is this :
DataClasses1DataContext db = new DataClasses1DataContext();
var q = from row in db.table1
group row by new { row.name }
into grp
select new
{
grp.Key.name,
sum = grp.Sum(row => row.calorie)
};
db.SubmitChanges();
Now you are just selecting data. You need the block for insertion like the following:
var q = (from row in db.table1
group row by new { row.id, row.name } into grp
select new
{
grp.Key.id,
grp.Key.name,
sum = grp.Sum(s => s.calorie)
}).ToList();
foreach(var item in q)
{
var e = new db.table2Entity
{
id = item.id,
name = item.name,
totalcalorie = item.sum
};
db.Table2.AddObject(e);
}
db.SaveChanges();
I think that you do not see the result on you databse after db.SubmitChanges() wright ? Linq query should work fine but Submit doesn't see the change becouse there is no change in table2. You only select data and group it from table1. Please debug and see what is in q variable.

Group by two columns in DataTable Column sum

In the following code for finding sum of Rate column in the DataTable dt:
dt.Compute("Sum(Convert(Rate, 'System.Int32'))");
In this is it possible to assign group by clause like SQL Inn order to get Sum based on a value in another column of the same dt Fo eg:
----------------------------
Rate | Group |type
----------------------------
100 | A | 1
120 | B | 2
70 | A | 1
50 | A | 2
----------------------------
I just wanna to get.
Sum A=170(type-1) SUMA=50(type-2) an Sum B=120(type-2)
Ref: I got ans in my previous question in single column case
Group by in DataTable Column sum.
You can group by an anonymous type:
var result = from r in dt.AsEnumerable()
group r by new { Group = r["Group"], Type = r["Type"] } into g
select new { Group = g.Key.Group,
Type = g.Key.Type,
Sum = g.Sum(x => Convert.ToInt32(x["Rate"])) };
foreach (var r in result)
{
Console.WriteLine("Group {0}, Type {1}, Sum {2}", r.Group, r.Type, r.Sum);
}

how to get some rows from dataset using sql sentence?

i have dataset that contains rows
MyTbl
=====
Name | Age
----------
aa | 23
bb | 90
cc | 2
dd | 1
ee | 14
i need to fill datagrid with all rows that the age > 5
aa | 23
bb | 90
ee | 14
i try this:
dataGrid1.DataSource = Main.dsParts.Tables[1].DefaultView.RowFilter = "Age > 5";
and this:
dataGrid1.DataSource = Main.dsParts.Tables[1].Select("Age > 5");
but it not work !, how to do it ?
thanks in advance
Try this:
Main.dsParts.Tables[1].DefaultView.RowFilter = "Age > 5";
dataGrid1.DataSource = Main.dsParts.Tables[1].DefaultView;
The RowFilter sets the condition, but just setting it doesn't return a new view to display; but from that point on, the .DefaultView will contain only those rows that match that criteria.

Categories