Join Tables in LINQ - c#

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.

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"] };

Linq Left join, where, group by, count()

I need help with doing a Left join in a linq statement. My T-sql query works as expected but I can't seem to get the wanted results from the Linq. I also realize that there are ton of questions like mine, but I can't seem to apply any of the solutions to my case.
Products table
+---+------------+-----------+
| |transportID | Type(int)|
+---+------------+-----------+
| 1 | 5 | 1 |
| 2 | 5 | 3 |
| 3 | 6 | 3 |
+---+------------+-----------+
Stores
+---+------------+-------------+
| |Name |Type1(string)|
+---+------------+-------------+
| 1 | Ho | 1 |
| 2 | He | 2 |
| 3 | Be | 3 |
| 4 | Ke | 4 |
| 5 | Fe | 5 |
+---+------------+-------------+
My wanted result is
+---+------------+-------------+
| |Type |Count |
+---+------------+-------------+
| 1 | 1 | 1 |
| 2 | 2 | 0 |
| 3 | 3 | 1 |
| 4 | 4 | 0 |
| 5 | 5 | 0 |
+---+------------+-------------+
My tsql that works as intended
SELECT
Type1,
Count(Pro.transportId) as Count
FROM dbo.stores as sto
left Join dbo.products as pro on (sto.Type1 = pro.Type AND pro.transportId=5)
Where Type1 is not null
group by Type1
ORDER BY Type1 * 1 ASC
My Linq attempt returns this.
+---+------------+-------------+
| |Type |Count |
+---+------------+-------------+
| 1 | 1 | 1 |
| 3 | 3 | 1 |
+---+------------+-------------+
Linq Statement.
var res = (from sto in _context.Stores
join pro in _context.Products on sto.Type1 equals System.Data.Objects.SqlClient.SqlFunctions.StringConvert((double)pro.Type).Trim()
where pro.transportId == transportId
group pro by pro.Type1 into pt1
select new TypeTransportation()
{
Type = pt1.Key, // Needs to be int
Count = pt1.Count()
}).ToList();
I've tried doing some defaultifempty but can't seem to make it work.
Here is MSDN link "How to: Perform Left Outer Joins" with LINQ: https://msdn.microsoft.com/en-gb/library/bb397895.aspx
You code should be like this:
var res = (from sto in _context.Stores
join pro in _context.Products on sto.Type1 equals System.Data.Objects.SqlClient.SqlFunctions.StringConvert((double)pro.Type).Trim() into grpJoin
from product in grpJoin.DefaultIfEmpty()
where product.transportId == transportId
group product by product.Type1 into pt1
select new TypeTransportation()
{
Type = pt1.Key, // Needs to be int
Count = pt1.Count()
}).ToList();
Wow .. lastly i did it ..
var transportId = 5;
var res = from s in _context.Stores
let Type = _context.Stores.Take(1).Select(x => s.Type1).Cast<int>().FirstOrDefault()
group Type by Type into pt1
select new TypeTransportation
{
Type = pt1.Key, // Needs to be int
Count = _context.Products.Where(i => i.transportId == transportId && i.Type == pt1.Key).Count()
};
foreach (var item in res)
{
Console.WriteLine(item.Type + " " + item.Count);
}
Console.ReadKey();
I can't do it in query syntax, but using extension method syntax it will be
var products = new[]
{
new {transportId = 5, Type = 1},
new {transportId = 5, Type = 3},
new {transportId = 6, Type = 3},
new {transportId = 5, Type = 3},
new {transportId = 5, Type = 5},
};
var stores = new[]
{
new {Name = "Ho", Type1 = "1"},
new {Name = "He", Type1 = "2"},
new {Name = "Be", Type1 = "3"},
new {Name = "Ke", Type1 = "4"},
new {Name = "Fe", Type1 = "5"},
};
var transportId = 5;
var res = stores
.GroupJoin(
inner: products
.Where(product =>
product.transportId == transportId),
innerKeySelector: product => product.Type,
outerKeySelector: store => Int32.Parse(store.Type1),
resultSelector: (store, storeProducts) =>
new
{
StoreType = store.Type1,
StoreName = store.Name,
ProductsCount = storeProducts.Count()
})
.ToList();
foreach (var item in res)
{
Console.WriteLine(item);
}
Just replace Int32.Parse with appropriate sql function call for actual DbContext query code.
With query syntax this is probably the best I can propose:
var res =
from store in stores
join product in
(from prod in products where prod.transportId == transportId select prod)
on store.Type1 equals product.Type.ToString() into storeProducts
select new
{
StoreType = store.Type1,
StoreName = store.Name,
ProductsCount = storeProducts.Count()
};
Basically you need to follow the left join pattern described in join clause (C# Reference). The only tricky part is the pro.transportId=5 condition in
left Join dbo.products as pro on (sto.Type1 = pro.Type AND pro.transportId=5)
The important thing is to not include it as where clause after the join.
One possible way to handle it is like this:
var res = (from sto in _context.Stores
join pro in _context.Products
on new { sto.Type1, transportId } equals
new { Type1 = pro.Type.ToString(), pro.transportId }
into storeProducts
from pro in storeProducts.DefaultIfEmpty()
group sto by sto.Type1 into pt
select new
{
Type = pt.Key, // the string value, there is no way to convert it to int inside the SQL
Count = pt.Count()
}).AsEnumerable() // switch to LINQ to Objects context
.Select(pt => new TypeTransportation()
{
Type = Convert.ToInt32(pt.Type), // do the conversion here
Count = pt.Count()
}).ToList();
or just apply it as where clause before the join:
var res = (from sto in _context.Stores
join pro in _context.Products.Where(p => p.transportId == transportId)
on sto.Type1 equals pro.Type.ToString()
into storeProducts
// the rest ... (same as in the first query)
Another detail to mention is that in order to make LEFT JOIN effectively apply, you need to group by the left table (Stores in your case) field (like in the original SQL query), thus ending up with a string key. If you wish to get the int key, there is no way to do it inside the db query, so you need to use a temporary projection, context switch and the final projection as shown above.
UPDATE: The last thing that I didn't realize initially is that the original SQL Count(Pro.transportId) is excluding NULLs from the right side of the join. So the final correct equivalent LINQ query is:
var res = (from sto in _context.Stores
join pro in _context.MyProducts
on new { sto.Type1, transportId } equals
new { Type1 = pro.Type.ToString(), pro.transportId }
into storeProducts
from pro in storeProducts.DefaultIfEmpty()
group new { sto, pro } by sto.Type1 into pt
select new
{
Type = pt.Key,
Count = pt.Sum(e => e.pro != null ? 1 : 0)
})
.AsEnumerable()
.Select(pt => new TypeTransportation()
{
Type = Convert.ToInt32(pt.Type),
Count = pt.Count
}).ToList();

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.

Converting SQL Join Query to Linq query

i want to join different column where the output would be this using linq
| Name | Address | Cellphone | Email |
| John | NY | n/a | johndoe#y.c |
| John | NY | 123456781 | n/a |
And i want my output to be one liner combined
| Name | Address | Cellphone | Email |
| John | NY | 123456781 | johndoe#y.c |
I Tried it on SQL server and this is the Query that answers the needed output
select a.ID, a.Name , a.Address ,(
SELECT wc1.[Values]
FROM Contact as wc1 where wc1.infoID = a.ID and wc1.ContactTypeID = 56) as Email
,(
SELECT wc1.[Values]
FROM Contact as wc1 where wc1.infoID = a.ID and wc1.ContactTypeID = 59) as Cellphone
from Info as a where a.ID = 100
Also tried it on Linq but it produces different row with same ID
var an = (from a in db.Info
join b in db.Contact on a.ID equals b.InfoID
where b.ContactTypeID == 56
|| b.ContactTypeID == 59
select new
{
a.ID,
a.LastName,
a.FirstName,
a.MiddleName,
b.ContactTypeID,
b.Values
}).ToList();
List<InfoList> wlist = new List<InfoList>();
foreach (var row in an)
{
InfoList ci = new InfoList
{
ID = row.ID,
Name = row.FirstName + " " + row.MiddleName + " " + row.LastName,
ContactType = GetLookupDisplayValById(row.ContactTypeID),
ContactValue = row.Values
};
wlist.Add(ci);
}
return Json(wlist.ToList(), JsonRequestBehavior.AllowGet);
Can someone help me translate this to a Linq Statement
Your SQL does not use JOIN, so why are you trying to introduce it in LINQ?
var an = (from a in db.Info
select new
{
a.ID,
a.LastName,
a.FirstName,
a.MiddleName,
Email = db.Contact.FirstOrDefault(b => b.InfoID == a.ID && b.ContactTypeIF == 56).Values,
Cellphone = db.Contact.FirstOrDefault(b => b.InfoID == a.ID && b.ContactTypeIF == 59).Values,
}).FirstOrDefault(x => x.ID == 100);
You can use the Pivot table the mentioned link shows how to use it: http://www.codeproject.com/Tips/500811/Simple-Way-To-Use-Pivot-In-SQL-Query

How to merge two datatables, which having different schema?

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.

Categories