Add entire row to DataTable at once using list - c#

I just want to add List as a DataTable entire row. here is the code which I have tried.
private static DataTable _table = new DataTable();
List<string> tempList = new List<string>();
// tempList = {"A1","A2","A3","A4","A5","A6"}
_table.Rows.Add(tempList);
Expected output:
col1|col2 |col3 |col4 |col5| col6
----+-----+-----+------+----+--
row1 A1 | A2 | A3 | A4 | A5 | A6
However this is not working for me. It will insert data collection to first column.
Actual output:
col1 |col2 |col3 |col4 |col5| col6
----------+-----+-----+------+----+--
row1 A1,A2,A3.| | | | |
Please help me to Add entire row using list. thank you

DataRowCollection.Add() Method expects Object[], so you should probably try:
_table.Rows.Add(tempList.ToArray());

Rows.Add() accepts parms[], you can achieve it by converting your list into an array.
_table.Rows.Add(tempList.ToArray());

DataTable dt = new DataTable();
dt.Columns.Add();
dt.Columns.Add();
dt.Columns.Add();
List<string> tempList = new List<string>() { "a", "b", "c" };
dt.Rows.Add(tempList.ToArray<string>());

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

Sort datatable based on value in the column

I have a datatable,
PId PName Qty
123 XYZ 2
223 ABC 4
434 PQR 33
I want to sort it on "PName" but not asc/ desc order,
If I pass PName as "PQR", then PQR should come first and then rest of the rows,
same if I pass "ABC" then "ABC" should come first and then rest of the rows.
Basically wants to reshuffle the rows where first row should be the "PName" which I am holding in a variable.
Thanks
Desired output
If I have "ABC", then the above datatable should reshuffle as,
PId PName Qty
223 ABC 4
123 XYZ 2
434 PQR 33
If I have "PQR", then the above datatable should reshuffle as,
PId PName Qty
434 PQR 33
123 XYZ 2
223 ABC 4
DataTable dt = new DataTable();
dt.Columns.Add("PId", typeof(Int32));
dt.Columns.Add("PName", typeof(string));
dt.Columns.Add("Qty", typeof(Int32));
dt.Rows.Add(123, "XYZ", 2);
dt.Rows.Add(223, "ABC", 4);
dt.Rows.Add(434, "PQR", 33);
var stkLists = dt.AsEnumerable().ToList();
var matchList = stkLists.Where(m => m["PName"].ToString().StartsWith("PQR")).ToList();
var FinalList = matchList.Concat(stkLists.Except(matchList).ToList());
Try like this:
DataTable dt = new DataTable();
dt.Columns.Add("PId", typeof(Int32));
dt.Columns.Add("PName", typeof(string));
dt.Columns.Add("Qty", typeof(Int32));
dt.Rows.Add(123, "XYZ", 2);
dt.Rows.Add(223, "ABC", 4);
dt.Rows.Add(434, "PQR", 33);
string Name = "PQR";
DataTable newDt = dt.Rows.Cast<DataRow>().Where(r => r.ItemArray[1] == Name).CopyToDataTable();
dt = dt.Rows.Cast<DataRow>().Where(r => r.ItemArray[1] != Name).CopyToDataTable();
newDt.Merge(dt);

How to add multi let operator and orderby in linq

I have more columns in datatable (about 100 columns). See examble below:
Column 1 | Column 2 | Column 3 | ..... | Column n
1;Nick | 1 | USA | ..... | Value 1
2;David | 2 | Reston | ..... | Value 2
3;Marry | 3 | Spain | ..... | Value 3
4;Join | 4 | Italy 3 | ..... Value 4
Dictionary<string, string > dict = new Dictionary<string, string>();
dict.Add("Column_1", "asc");
dict.Add("Column_2", "asc");
dict.Add("Column_1", "desc");
...................
dict.Add("Column_n", "asc");
var myRows = from row in datatable.AsEnumerable()
let myID = int.Parse(row.Field<string>("Column 2"))
let name = row.Field<string>("Column 1").Split(';')[1]
....
orderby myID ascending, name descending, ......, column n asc
select row;
My problem is how to loop all items in Dictionary to add more let statements and orderby all columns in Dictionary.
Please help me to fix it. My english is not good, sorry
Dictionary<string, string > dict = new Dictionary<string, string>();
dict.Add("col1", "ASC");
dict.Add("col2", "ASC");
dict.Add("col3", "DESC");
DataTable dt = new DataTable();
dt.Columns.Add("col1");
dt.Columns.Add("col2");
dt.Columns.Add("col3");
Random r = new Random();
for (int i = 0; i < 20; i++)
dt.Rows.Add(r.Next(10), r.Next(4), r.Next(2));
string sort = "";
foreach (KeyValuePair<string, string> entry in dict)
sort = sort + " " + entry.Key + " " + entry.Value + ",";
sort = sort.Substring(0, sort.Length - 1).Trim();
dt.DefaultView.Sort = sort;
dt = dt.DefaultView.ToTable();

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.

how to fill each Column in datatable

I am iterating on a lot of strings and I want to fill my first(and only) 3 Columns with each result and then start again in a new row. like:
A | B | C
------+--------+------
"DOG" | "CAT" | "FISH"
"FDF" | "AAA" | "RRR"
AND SO ON....
Basically after each row is "full" open new row.
HtmlNodeCollection tables = doc.DocumentNode.SelectNodes("//table");
HtmlNodeCollection rows = tables[2].SelectNodes(".//tr");
DataTable dataTable = new DataTable();
dataTable.Columns.Add("A", typeof(string));
dataTable.Columns.Add("B", typeof(string));
dataTable.Columns.Add("C", typeof(string))
try like this
for (int i = 0; i < rows .Count(); i++)
{
DataRow datarowObj= dataTable .NewRow();
datarowObj["A"] = yourValue;
datarowObj["B"] = yourValue;
datarowObj["C"] = yourValue;
dataTable.Rows.Add(datarowObj);
}
You could use Linq's GroupBy to split the long list into groups of 3:
sample-data:
DataTable table = new DataTable();
table.Columns.Add("Col1");
table.Columns.Add("Col2");
table.Columns.Add("Col3");
List<string> longList = Enumerable.Range(1, 99).Select(i => "row " + i).ToList();
group the long list into parts of three:
var groupsWithThree = longList
.Select((s, i) => new { Str = s, Index = i })
.GroupBy(x => x.Index / 3);
add them to the table:
foreach (var group3 in groupsWithThree)
table.Rows.Add(group3.First().Str, group3.ElementAt(1).Str, group3.Last().Str);
Note that it presumes that the list is divisible by three.
Manage with DataRoxw, for instance, after adding an empty DataRow to your DataTable :
DataRow row = table.Rows[0];
foreach (object item in row.ItemArray)
{
?
dataTable.Rows.Add(new object[] { "A1", "B1", "C1" })
// Alternatively
object[] arr = new object[] { "A2", "B2", "C2" };
dataTable.Rows.Add(arr);

Categories