How to join multiple tables into one - c#

How do I join multiple tables into one?
I have 3 Datatables with column names: Test 1, Test 2 and Test3
The Datatables got 3 rows with values.
I want them in one datatable like the example below
TEST 1 | TEST2 | TEST 3
I've tried the merge function dt1.merge(dt2) but it adds additional 3 rows to every column.
The table is for DataGridView.
This is the code example on how i retrieve the table from the database.
string queryStatusTest =
"SELECT status AS 'uppgift " + t +"' FROM b_personuppgift
WHERE uppgiftid IN(SELECT uppgiftid FROM b_uppgift
WHERE kursid = 'ABC123') "
+ "AND uppgiftid=" + t + " ORDER BY uppgiftid";
DataTable dTest = dataBase.Select(queryStatusTest);
The database.Select() function returns only one table.

Assume 3 columns type are string:
var mergeTable = dt1.AsEnumerable()
.Concat(dt2.AsEnumerable())
.Concat(dt3.AsEnumerable())
.GroupBy(row => new {
Test1 = row.Field<string>("Test1")
Test2 = row.Field<string>("Test2")
Test3 = row.Field<string>("Test3")
})
.Select(g => g.First())
.CopyToDataTable();

I guess that saying database you mean table. You can insert data from all 3 tables into one using this statement:
INSERT INTO table_all(column1,column2,column3)
VALUES(
(SELECT column1 FROM test1),
(SELECT column1 FROM test2),
(SELECT column1 FROM test3),
)

The most common reason for this problem is that you haven't set the primary key on the DataTables. The Merge method uses the primary key to match rows.
The Merge method documentation in MSDN states:
When merging a new source DataTable into the target, any source rows
with a DataRowState value of Unchanged, Modified, or Deleted, is
matched to target rows with the same primary key values. Source rows
with a DataRowState value of Added are matched to new target rows with
the same primary key values as the new source rows.

Related

Create an id autoincrement with dapper

I'm working with Dapper and .Net 6.0... I have to do an insert from table1 to table2... in the insert the columns match each other... the only column is "toID" of table1... which does NOT match the column of table2 (that's why I put a 4 in it) but I have to make it auto-increment so that for each insert there is an incrementing sequence
var sql =
$"INSERT INTO table1 (toId,teId,dateShift,SectorOrigen) SELECT 4,teID,#dateModify,#LastSector FROM table2";
That is to say... that when I generate an insert the ID = 1, then another ID = 2 and so on continuously
Any advice??
You can create and use the sequence https://learn.microsoft.com/en-us/sql/t-sql/statements/create-sequence-transact-sql?view=sql-server-ver16

Compare Data tables

I need to compare the two data table,
In both datatable we have the systemuserid . In datatable1 we have two rows.The system user id will start with c2dd... and 53cf...
Now i need to compare the two tables whther all systemuserids are available in second Datatable.
In these table the c2dd... sustem user is not available in the datatable 2. so i need to add that c2dd.. row in datatable 2 with noofCall as 0
If you have two datatable available, then you can compare two table and get table1 row systemuserid which are not available in table2 in following way :
IEnumerable<DataRow> differenceRows = table1.AsEnumerable()
.Where(x => table2.AsEnumerable()
.All(y => y.Field<string>("systemuserid") != x.Field<string>("systemuserid")));
After getting differenceRows, you can add new row in table2 iterating through differenceRows.

Duplicates In DataTable, Getting Last By Specifying Two Properties

I have a DataTable, with two columns of type String named ID and Value. These values are not required to be unique.
As I add to my DataTable throughout my application, at some point I am trying to get the last item that was added that meets the value of the two properties. For example, for all records where ID = 1 and Value = 2, there may be several. I need the last record.
I have been trying to use LINQ groupbys, the MyDataTable variable is my datatable.:
var groupQuery = from table in MyDataTable.AsEnumerable()
group table by new {column1 = table["PERSON_GU"], column2 = table["FIELD"]}
into groupedTable
select new
{
x = groupedTable.Key, // Each Key contains column1 and column2
y = groupedTable.Count()
};
I cant figure out how to make this select last though, it appears to return an anonymous type which is a little out of my development skill wheelhouse.
In summary, I have a datatable with two columns, I am trying to group my final datatable by these column values, and then get the last item.
If you want the last DataRow of each group:
var groupQuery =
from table in MyDataTable.AsEnumerable()
group table by new {column1 = table["PERSON_GU"], column2 = table["FIELD"]}
into groupedTable
select groupedTable.Last();

Merging 2 datatables in to 1 datatable with same number of rows.

How can i merge two Datatables into the same row. I am using different stored procedures to get data into datasets. In asp.net using c#, i want to merge them so there are same number of rows as table 1 with an added column from table 2.
For example:
DataTable table1 = dsnew.Tables[0];
DataTable table2 = dsSpotsLeft.Tables[0];
table1.Merge(table2);
This is fetching me 4 rows instead of 2 rows. What am i missing here? Thanks in advance!!
You cannot use the method Merge in this case, instead you should create new DataTable dt3, and then add columns and rows based on the table 1 and 2:
var dt3 = new DataTable();
var columns = dt1.Columns.Cast<DataColumn>()
.Concat(dt2.Columns.Cast<DataColumn>());
foreach (var column in columns)
{
dt3.Columns.Add(column.ColumnName, column.DataType);
}
//TODO Check if dt2 has more rows than dt1...
for (int i = 0; i < dt1.Rows.Count; i++)
{
var row = dt3.NewRow();
row.ItemArray = dt1.Rows[i].ItemArray
.Concat(dt2.Rows[i].ItemArray).ToArray();
dt3.Rows.Add(row);
}
Without knowing more about the design of these tables, some of this is speculation.
What it sounds like you want to perform is a JOIN. For example, if you have one table that looks like:
StateId, StateName
and another table that looks like
EmployeeId, EmployeeName, StateId
and you want to end up with a result set that looks like
EmployeeId, EmployeeName, StateId, StateName
You would perform the following query:
SELECT Employee.EmployeeId, Employee.EmployeeName, Employee.StateId, State.StateName
FROM Employee
INNER JOIN State ON Employee.StateId = State.StateId
This gives you a resultset but doesn't update any data. Again, speculating on your dataset, I'm assuming that your version of the Employee table might look like the resultset:
EmployeeId, EmployeeName, StateId, StateName
but with StateName in need of being populated. In this case, you could write the query:
UPDATE Employee
SET Employee.StateName = State.StateName
FROM Employee
INNER JOIN State ON Employee.StateId = State.StateId
Tested in SQL Server.
Assuming you have table Category and Product related by CategoryID, then try this
var joined = from p in prod.AsEnumerable()
join c in categ.AsEnumerable()
on p["categid"] equals c["categid"]
select new
{
ProductName = p["prodname"],
Category = c["name"]
};
var myjoined = joined.ToList();
Sources
LINQ query on a DataTable
Inner join of DataTables in C#
http://social.msdn.microsoft.com/Forums/en-US/adodotnetdataset/thread/ecb6a83d-b9b0-4e64-8107-1ca8757fe58c/
That was a LINQ solution. You can also loop through the first datatable and add columns from the second datatable

How to Filter dataset for two column

I have datatable which is binded with grid as following
Table1
Id Type Desc
1 A ABC
2 A XYZ
1 B QRS
3 B 123
Based upon the user selection on Grid row following table is generating.
Table2
Id Type
1 A
1 B
2 A
This second table can grow till first table.
I have to find out filtered rows from table 1 based upon selection of grid (or output as table2)
I have following questions
Should i create second table2 from rows selection of grid to filter table1
If yes, then how to filter with these two table
If No answer of question1 then what is best way.
I am using dEV eX GRID.
you can use a dataview and set correctly the RowFilter property to filter your first datable
with filter value of second table,for instance:
dataView.RowFilter = "Id IN (1, 2) AND Type = A"
for sure you have to make it dynamic so you can scan each row and
make your rowFilter that is id = 1 and type = A or id = 2 and type = A etc...
here a link to understand how use it:
http://www.csharp-examples.net/dataview-rowfilter/

Categories

Resources