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);
Related
Gender Age Category
--------------------------------
Male | 10 | 2
Female | 15 | 1
Trans | 13 | 3
Female | 10 | 1
Male | 20 | 2
i have a datatable with above values. Male CategoryId is 2. in above table there are total 2 Males rows. based on Category, merged two rows and divide into a seperate datatable.
My required output is :-
Datatable 1
Gender Age Category
--------------------------------
Male | 10 | 2
Male | 20 | 2
DataTable 2
Gender Age Category
--------------------------------
Female | 15 | 1
Female | 10 | 1
DataTable 3
Gender Age Category
--------------------------------
Trans | 13 | 3
var view = sourceDataTable.DefaultView;
view.RowFilter = "Category = 2";
var maleDataTable = view.ToTable();
view.RowFilter = "Category = 1";
var femaleDataTable = view.ToTable();
view.RowFilter = "Category = 3";
var transDataTable = view.ToTable();
Here you go:
List<DataTable> result = DTHead.AsEnumerable()
.GroupBy(row => row.Field<DataType>("Category"))
.Select(g => g.CopyToDataTable())
.ToList();
For more details please check this post:Split Tables
See following :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
namespace ConsoleApplication48
{
class Program
{
static void Main(string[] args)
{
DataTable dt = new DataTable();
dt.Columns.Add("Gender", typeof(string));
dt.Columns.Add("Age", typeof(int));
dt.Columns.Add("Category", typeof(int));
dt.Rows.Add(new object[] {"Male", 10, 2});
dt.Rows.Add(new object[] {"Female", 15, 1});
dt.Rows.Add(new object[] {"Trans", 13, 3});
dt.Rows.Add(new object[] {"Female", 10, 1});
dt.Rows.Add(new object[] {"Male", 20, 2});
DataTable dt1 = dt.AsEnumerable().Where(x => x.Field<string>("Gender") == "Male").CopyToDataTable();
DataTable dt2 = dt.AsEnumerable().Where(x => x.Field<string>("Gender") == "Feale").CopyToDataTable();
DataTable dt3 = dt.AsEnumerable().Where(x => x.Field<string>("Gender") == "Trans").CopyToDataTable();
}
}
}
Here is a more generic solution that get every type in a column :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
namespace ConsoleApplication48
{
class Program
{
static void Main(string[] args)
{
DataTable dt = new DataTable();
dt.Columns.Add("Gender", typeof(string));
dt.Columns.Add("Age", typeof(int));
dt.Columns.Add("Category", typeof(int));
dt.Rows.Add(new object[] { "Male", 10, 2 });
dt.Rows.Add(new object[] { "Female", 15, 1 });
dt.Rows.Add(new object[] { "Trans", 13, 3 });
dt.Rows.Add(new object[] { "Female", 10, 1 });
dt.Rows.Add(new object[] { "Male", 20, 2 });
//updated code
string[] rowNames = dt.AsEnumerable().Select(x => x.Field<string>("Gender")).Distinct().ToArray();
DataSet ds = new DataSet();
foreach (string gender in rowNames)
{
DataTable newDt = dt.AsEnumerable().Where(x => x.Field<string>("Gender") == gender).CopyToDataTable();
newDt.TableName = gender;
ds.Tables.Add(newDt);
}
}
}
}
I have two DataTables being filled.
DT1 and DT2
Each DataTable has the same column headers. However, DT2 may or may not have the same amount of rows.
ID | Type | Value
I need the new Table to add Rows as necessary based on the number of results that are returned in the "Type" column and set DT3 rows ID = DT1.ID and Value to "N/A"
DT1 DT2 DT3
ID | Type | Value ID | Type | Value ID | Type | Value
1 ItemCost 5000 27 ItemCost 3800 27 ItemCost 3800
2 TravCost 5700 28 TravCost 4851 28 TravCost 4851
3 UpCharge 3600 3 UpCharge N/A
4 TaxCost 7000 4 TaxCost N/A
Here is my code for this issue:
DataTable dt1 = new DataTable();
dt1.Columns.Add("ID");
dt1.Columns.Add("Type");
dt1.Columns.Add("Value");
dt1.Rows.Add(new Object[] { "1", "ItemCost", "5000" });
dt1.Rows.Add(new Object[] { "2", "TravCost", "5700" });
dt1.Rows.Add(new Object[] { "3", "UpCharge", "3600" });
dt1.Rows.Add(new Object[] { "4", "TaxCost", "7000" });
DataTable dt2 = new DataTable();
dt2.Columns.Add("ID");
dt2.Columns.Add("Type");
dt2.Columns.Add("Value");
dt2.Rows.Add(new Object[] { "27", "ItemCost", "3800" });
dt2.Rows.Add(new Object[] { "28", "TravCost", "4851" });
DataTable dt3 = new DataTable();
dt3 = dt2.Clone();
foreach (DataRow item in dt2.Rows)
{
dt3.Rows.Add(new object[] { item["ID"], item["Type"], item["Value"] });
}
foreach (DataRow item in dt1.Rows)
{
DataRow[] drs = dt3.Select("Type='" + item["Type"].ToString() + "'");
if (drs.Count() == 0)
{
dt3.Rows.Add(new object[] { item["ID"], item["Type"], "N/A" });
}
}
MasterData
Id Name
1 CENTRAL
2 EAST
3 EAST CENTRAL
4 EAST COASTAL
5 NORTH
6 NORTH WEST
7 SOUTH
8 SOUTH CENTRAL
9 WEST
Data Received
Id Name Value
1 CENTRAL 125.65
5 NORTH 553.21
i want the Result to be as followes
Id Name Value
1 CENTRAL 125.65
2 EAST 0.0
3 EAST CENTRAL 0.0
4 EAST COASTAL 0.0
5 NORTH 553.21
6 NORTH WEST 0.0
7 SOUTH 0.0
8 SOUTH CENTRAL 0.0
9 WEST 0.0
Please note all are Datatable how can i Get the Result
Let say your DataTable are declared as following:
var dt1 = new DataTable();
dt1.Columns.Add(new DataColumn("Id", typeof(int)));
dt1.Columns.Add(new DataColumn("Name", typeof(string)));
var dt2 = new DataTable();
dt2.Columns.Add(new DataColumn("Id", typeof(int)));
dt2.Columns.Add(new DataColumn("Name", typeof(string)));
dt2.Columns.Add(new DataColumn("Value", typeof(double)));
You can join it and get what you want with LINQ to objects:
var query = from r1 in dt1.AsEnumerable()
join r2 in dt2.AsEnumerable() on r1.Field<int>("Id") equals r2.Field<int>("Id") into r3
from r4 in r3.DefaultIfEmpty()
select new
{
Id = r1.Field<int>("Id"),
Name = r1.Field<string>("Name"),
Value = r4 == null ? 0.00 : r4.Field<double>("Value")
};
With that IEnumerable<Anonymous_Type> you can get DataTable object back, using ToDataTable<T> extension method:
public static class EnumerableToDataTableConverter
{
public static DataTable ToDataTable<T>(this IEnumerable<T> items)
{
DataTable dataTable = new DataTable(typeof(T).Name);
//Get all the properties
PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo prop in Props)
{
//Setting column names as Property names
dataTable.Columns.Add(prop.Name);
}
foreach (T item in items)
{
var newRow = dataTable.NewRow();
for (int i = 0; i < Props.Length; i++)
{
//inserting property values to datatable rows
newRow[Props[i].Name] = Props[i].GetValue(item, null);
}
dataTable.Rows.Add(newRow);
}
//put a breakpoint here and check datatable
return dataTable;
}
}
You can get DataTable from query with following statement:
var result = query.ToDataTable();
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>());
I have a datatable filled with staff data like..
Staff 1 - Day 1 - Total
Staff 1 - Day 2 - Total
Staff 1 - Day 3 - Total
Staff 2 - Day 1 - Total
Staff 2 - Day 2 - Total
Staff 2 - Day 3 - Total
Staff 2 - Day 4 - Total
I want to modify so that the result would be sth like..
Staff 1 - Day 1 - Total
Staff 1 - Day 2 - Total
Staff 1 - Day 3 - Total
Total - - Total Value
Staff 2 - Day 1 - Total
Staff 2 - Day 2 - Total
Staff 2 - Day 3 - Total
Staff 2 - Day 4 - Total
Total - - Total Value
to be concluded, I need to insert the total row at the end of each staff record.
So, my question is how to insert a row into a datatable? Tkz..
#William You can use NewRow method of the datatable to get a blank datarow and with the schema as that of the datatable. You can populate this datarow and then add the row to the datatable using .Rows.Add(DataRow) OR .Rows.InsertAt(DataRow, Position). The following is a stub code which you can modify as per your convenience.
//Creating dummy datatable for testing
DataTable dt = new DataTable();
DataColumn dc = new DataColumn("col1", typeof(String));
dt.Columns.Add(dc);
dc = new DataColumn("col2", typeof(String));
dt.Columns.Add(dc);
dc = new DataColumn("col3", typeof(String));
dt.Columns.Add(dc);
dc = new DataColumn("col4", typeof(String));
dt.Columns.Add(dc);
DataRow dr = dt.NewRow();
dr[0] = "coldata1";
dr[1] = "coldata2";
dr[2] = "coldata3";
dr[3] = "coldata4";
dt.Rows.Add(dr);//this will add the row at the end of the datatable
//OR
int yourPosition = 0;
dt.Rows.InsertAt(dr, yourPosition);
// get the data table
DataTable dt = ...;
// generate the data you want to insert
DataRow toInsert = dt.NewRow();
// insert in the desired place
dt.Rows.InsertAt(toInsert, index);
// create table
var dt = new System.Data.DataTable("tableName");
// create fields
dt.Columns.Add("field1", typeof(int));
dt.Columns.Add("field2", typeof(string));
dt.Columns.Add("field3", typeof(DateTime));
// insert row values
dt.Rows.Add(new Object[]{
123456,
"test",
DateTime.Now
});
In c# following code insert data into datatable on specified position
DataTable dt = new DataTable();
dt.Columns.Add("SL");
dt.Columns.Add("Amount");
dt.rows.add(1, 1000)
dt.rows.add(2, 2000)
dt.Rows.InsertAt(dt.NewRow(), 3);
var rowPosition = 3;
dt.Rows[rowPosition][dt.Columns.IndexOf("SL")] = 3;
dt.Rows[rowPosition][dt.Columns.IndexOf("Amount")] = 3000;
You can do this, I am using
DataTable 1.10.5
using this code:
var versionNo = $.fn.dataTable.version;
alert(versionNo);
This is how I insert new record on my DataTable using row.add (My table has 10 columns), which can also includes HTML tag elements:
function fncInsertNew() {
var table = $('#tblRecord').DataTable();
table.row.add([
"Tiger Nixon",
"System Architect",
"$3,120",
"2011/04/25",
"Edinburgh",
"5421",
"Tiger Nixon",
"System Architect",
"$3,120",
"<p>Hello</p>"
]).draw();
}
For multiple inserts at the same time, use rows.add instead:
var table = $('#tblRecord').DataTable();
table.rows.add( [ {
"Tiger Nixon",
"System Architect",
"$3,120",
"2011/04/25",
"Edinburgh",
"5421"
}, {
"Garrett Winters",
"Director",
"$5,300",
"2011/07/25",
"Edinburgh",
"8422"
}]).draw();