Combine two datatable with common column c# - c#

I have two table as below
Table1
IntervalID(pK)
1
2
3
Table 2
IntervalID Name
1 XXX
Output should be (Table1+Table2)
IntervalID Name
1 XXX
2 NULL
3 NULL
I have done like below
Table1.Merge(Table2);
But it does not give desired output

You could achieve this by using Left join, like the following code:
var result = (from t1 in table1
join t2 in table2 on t1.IntervalId equals t2.IntervalId into leftedResults
from leftedResult in leftedResults.DefaultIfEmpty()
select new { t1.IntervalId, Name = leftedResult?.Name }).ToList();
Note that, you can't merge two DataTables that not have similar schemas.
Left join for DataTables :
var result = (from t1 in dataTable1.AsEnumerable()
join t2 in dataTable2.AsEnumerable() on t1.Field<int>("IntervalId") equals t2.Field<int>("IntervalId") into leftedResults
from leftedReult in leftedResults.DefaultIfEmpty()
select new { IntervalId = t1.Field<int>("IntervalId"), Name = leftedReult?.Field<string>("Name") }).ToList();
I hope you find this helpful.

Related

How to JOIN two data tables using LINQ and Where condition?

I have two data tables as following
TableA TableB
UID QID
QID Value1
Value2
I want to join two data tables and get Value1 and Value 2. I tried the following, but I am not getting any data back.
string str = "AAA";
var result = (from t1 in TableA.AsEnumerable()
//join between two tables
join t2 in TableB.AsEnumerable() on t1.Field<string>("UID") equals t2.Field<string>("QID")
//where conditions
where t2.Field<string>("QID") == str && t1.Field<string>("QID") == "ABCD"
//select clause
select t2.Field<string>("Value1"));
This is my query with out using LINQ and its working.
Select t2.Value1, t2.value2 from TableA t1 JOIN TableB t2 ON t2.QID = t1.UID WHERE t2.QID = 'AAAAA' AND t1.QID = 'XXXX'
Thanks for your help.
Your LINQ code should work, I guess you just need to use the same where the condition values for QID.
where t2.Field<string>("QID") == "AAA" && t1.Field<string>("QID") == "ABCD"
is not equal to your SQL:
WHERE t2.QID = 'AAAAA' AND t1.QID = 'XXXX'
It should work when you set correct values in LINQ

LINQ to SQL Join orderby

i am new to LINQ and joins, so Please forgive me if I am asking it wrong.
I have two tables
Table1
id name date
1 Mike 20-10-15
2 John 21-10-15
3 Sam 23-10-15
Table2
id name date
1 Ashle 19-10-15
2 Lily 21-10-15
3 Jeni 22-10-15
4 April 23-10-15
I need 5 records using Joins and should be orderby Date, most recent records.
Can you guys help me, I really need to figure out how Joins works with orderby.
Thanks
EDIT:
They are two different tables so no foreign key, so I think I can't use Join, so so far what I have done is like this
var combinddata = (from t1 in db.Table1
select t1.id)
.Concat(from t2 in db.Table2
select t2.id);
I don't know how to get only 5 records how to compare records from both tables on DateTime base.
Output should be
Sam
April
Jeni
John
Lily
You can concatenate equal anonymous types from different tables. If you also select the dates, you can sort by them, in descending order, and take the first 5 records:
Table1.Select (t1 =>
new
{
Id = t1.Id,
Name = t1.Name,
Date = t1.Date
}
).Concat(
Table2.Select (t2 =>
new
{
Id = t2.Id,
Name = t2.Name,
Date = t2.Date
}
))
.OrderByDescending (x => x.Date).Take(5)
Note that this gives precedence to items in Table1. If item 5 and 6 in the concatenated result are on the same date, but from Table1 and Table2, respectively, you only get the item from Table1.
If you want, you can select only the names from this result, but I assume that your output only shows the intended order of record, not the exact expected result.
var query =
from Table1 in table1
join Table2 in table2 on table1.id equals table2.id
orderby table1.date ascending
select table1.date;
Try this way
var combinddata = (from t1 in db.Table1
select t1.Name)
.Concat(from t2 in db.Table2
select t2.Name).OrderByDescending(x => x.date).Take(5);

How to combine and retrieve multiple columns from two tables in a Dataset

I have a DataSet with two tables connected by a reference (Loop_id)
Table1
Column1 Column2 Loop_id
1 ItemCode_AAA 6
2 ItemCode_BBB 8
Table2
Column1 Loop_id
2014-Sep-09 6
2014-Nov-09 8
How do I retrieve all the columns, except loop_id from both tables to single table.
The resulting table should appear like
T1_Column1 T1_Column2 T2_Column1
1 ItemCode_AAA 2014-Sep-09
2 ItemCode_BBB 2014-Nov-09
I am using Net Framework 4.5
Use Linq to DataSets:
To enumerate the table, call AsEnumerable.
DataTable table1 = ds.Tables["table1"];
DataTable table2 = ds.Tables["table2"];
var records = (from t1 in table1.AsEnumerable()
join t2 in table2.AsEnumerable()
on t1.Field<int>("Loop_id") equals t2.Field<int>("Loop_id")
select new {T1_Column1 = t1.Field<string>("Column1"),
T2_Column2 = t2.Field<string>("Column2"),
T2_Column1 = t2.Field<string>("Column1")});
Use View
Or you can use join
SELECT T1.Column1 AS T1_Col , T1.Column2 AS T1_Col , T2.Column1 AS T2_Col
FROM dbo.Table1 AS T1 RIGHT OUTER JOIN
dbo.Table2 AS T2 ON dbo.T1.Loop_id = dbo.T2.Loop_id

Outer Join in Linq or EF

I have two tables
T1 T2
-------------
id1 id2
-----------
1 3
2 5
3
4
I want to get a outer join so that I get 1,2,3,4,5
I am using following Linq command
var newList = (from i in T1
join d in T2
on i.id1 equals d.id2 into output
from j in output.DefaultIfEmpty()
select new {i.id});
The out put I get i 1,2,3,4 missing 5. How can I get it to give me newList 1,2,3,4,5
Help Please
There is no direct alternative to OUTER JOIN in LINQ. You have to solve it like this:
Within query you wrote only the i's that also exists in T2 because of the on i.id1 equals d.id2.
var result = T1.Select(item => item.id1).Union(T2.Select(item => item.id2));
You could use Union like:
var result = T1.Union(T2);
You can refer to this C# linq union question

Perform Join and Group with Linq to SQL?

Hey all. I'm not sure how I could express the following query in C# using Linq to SQL. Here is a short snippet of the pure SQL:
select t1.WholesalerID, t1.RetailerID,
sum(t1.Col1) as 'Column 1',
sum(t2.Col1) as 'Other Column 1',
(sum(t1.Col1) - sum(t2.Col1)) as 'Column 1 Difference',
sum(t1.Col2) as 'Column 2',
sum(t2.Col2) as 'Other Column 2',
(sum(t1.Col2) - sum(t2.Col2)) as 'Column 2 Difference'
from Table1 t1
inner join Table2 t2 on t1.WholesalerID = t2.WholesalerID
group by t1.WholesalerID, t1.RetailerID
Now, I've done Linq to SQL joins and group by's before, but I'm sure how to go about doing these together. I run into the problem when I'm attempting to sum the values from the joined tables. Thanks.
I've reached this solution: (didn't tested it though)
var qry = from t in
(from t1 in Table1
join t2 in Table2 on t1.WholesalerID equals t2.WholesalerID
select new { t1, t2 })
group t by new { t.t1.WholesalerID, t.t1.RetailerID } into g
select new MyTypeWithDifferenceProp
{
WholesalerID = g.Key.WholesalerID,
RetailerID = g.Key.RetailerID,
Column1 = g.Sum(e => e.t1.Col1),
OtherColumn1 = g.Sum(e => e.t2.Col1),
Column2 = g.Sum(e => e.t1.Col2),
OtherColumn2 = g.Sum(e => e.t2.Col2),
};
This MyTypeWithDifferenceProp would have the Column1Difference and Column2Difference already defined.

Categories

Resources