I have a DataTable called “DTHead” which has the following records,
MIVID Quantity Value ------ ---------- -------- 1 10 3000 1 20 3500 1 15 2000 2 20 3000 2 50 7500 3 25 2000
Here, I need to split the above DataTable into three tables based on the MIVID such as follows;
DTChild1:
MIVID Quantity Value ------- ---------- --------- 1 10 3000 1 20 3500 1 15 2000
DTChild2:
MIVID Quantity Value ------- ---------- --------- 2 20 3000 2 50 7500
DTChild3:
MIVID Quantity Value
------- ---------- ---------
3 25 2000
Suppose, if the Header DataTable contains 4 different MIVID means, then 4 Child DataTable should be created based on the MIVID. How to do this?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Use LINQ to DataTable to group the first column by GroupBy, and use method CopyToDataTable to copy list of rows to DataTable
List<DataTable> result = DTHead.AsEnumerable()
.GroupBy(row => row.Field<int>("MIVID"))
.Select(g => g.CopyToDataTable())
.ToList();
Then you can get the result as a list of DataTables as you expected.
Method 2
DataTable tbl = new DataTable("Data").AsEnumerable()
.Where(r => r.Field<int>("ParentId") == 1) // ParentId == 1
.Where(r => r.Field<int>("Id") > 3) // Id > 3
.Where(r => r.Field<string>("Name").Contains("L")) // Name contains L
.OrderBy(r => r.Field<int>("Id")) // Order by Id
.CopyToDataTable();
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0