What is the fastest way to convert anonymous type to DataTable?
Update:
I want to get and populate DataTable from anonymous type. If reflection is neccesary, how can I to do it using reflection?
Found here:
var result = from p in dataSource
group p by p.City into cities
select new { Property1 = cities.Key, Property 2= cities.Average(p => p.Age) };
dt.Columns.Add("Property1");
dt.Columns.Add("Property2");
foreach (var item in result)
{
dt.Rows.Add(item.Property1,item.Property2);
}
See here for a generic solution: Convert generic List/Enumerable to DataTable?
///fill dt1
Dim dt1 As New DataTable dt1 = connection.LoadPoliceData("")
///fll dt2
Dim dt2 As New DataTable dt2 = connection.LoadDataCompare("")
////fill enumerable data(anonymous data) in dt , using linq query
Dim dt As New DataTable
dt.Columns.Add("Name", GetType(String))
dt.Columns.Add("Mobile", GetType(String))
Dim data1 = (From datarow1 In dt1.AsEnumerable Join datarow2 In dt2.AsEnumerable
On datarow1.Field(Of String)("NameofPerson") Equals datarow2.Field(Of String)("Name") And datarow1.Field(Of String)("Mobile") Equals datarow2.Field(Of String)("MobileNumber")
Select dt.LoadDataRow(New Object() {datarow1.Field(Of String)("NameofPerson"), datarow2.Field(Of String)("MobileNumber")}, False)).Distinct().ToList()
Dim i = dt.Rows.Count
record in dt(datatable variable )
///summary fill datatable one (dt1)
Dim dt1 As New DataTable
dt1 = connection.LoadPoliceData("")
///summary fill datatable one (dt2)
Dim dt2 As New DataTable
dt2 = connection.LoadDataCompare("")
/// summary declare datatable save . where i want fill Enumerable data
Dim save As New DataTable
save.Columns.Add("Name", GetType(String))
save.Columns.Add("Mobile", GetType(String))
///summary writing linq query with join of dt1 and dt2 , And datatable(save)
Dim data1 = (From datarow1 In dt1.AsEnumerable
Join datarow2 In dt2.AsEnumerable
On datarow1.Field(Of String)("NameofPerson") Equals datarow2.Field(Of String)("Name") And datarow1.Field(Of String)("Mobile") Equals datarow2.Field(Of String)("MobileNumber")
Select save.LoadDataRow(New Object() {datarow1.Field(Of String)("NameofPerson"), datarow2.Field(Of String)("MobileNumber")}, False)).Distinct().ToList()
///summary count of datatable save
Dim i = save.Rows.Count
Related
I need to initialize multiple objects like this.
DataTable dt1 = new DataTable();
DataTable dt2 = new DataTable();
DataTable dt3 = new DataTable();
DataTable dt4 = new DataTable();
Is there a way to initialize them as
DataTable dt1, dt2, dt3, dt4 = new DataTable();
If I use above, there are no compile errors but there are runtime errors says An Object reference not set to an instance.
How can I achieve this.
No, thereĀ“s no such way, you have to initialize them one by one.
Your error appears because dt1 to dt3 are initialized to null, only dt4 has a value. Thus doing anything with d1 will throw a NullReferenceException.
But you can do so in a single line:
DataTable t1 = new DataTable(), t2 = new DataTable(), t3 = new DataTable(), t4 = new DataTable();
Even better would be a list/array:
var tables = new[] { new DataTable(), new DataTdable(), new DataTable(), new DataTable() };
or even
var tables = Enumerable.Range(0, 4).Select(x => new DataTable());
I have two datatable DurationByCurrency(inside a dataset) and Fund which looks like below
I want to delete the rows in Duration By Currency Datatable whose FundCode has value as 2 in Fund Dt by performing a join.
var result = from table1 in raptorDS.Tables[RaptorTable.DurationByCurrency].AsEnumerable()
join table2 in fundDT.AsEnumerable()
on table1.Field<string>("FundCode") equals table2.Field<string>("FundCode") into ps
from row in ps.DefaultIfEmpty()
{
//delete query
}
Please help me on this as I am new to LINQ.
var result = from row1 in raptorDS.Tables[RaptorTable.DurationByCurrency].AsEnumerable()
join row2 in fundDT.AsEnumerable()
on row1.Field<string>("FundCode") equals row2.Field<string>("FundCode")
where row1.Field<string>("value")
equals "2" select row1;
result.ToList().ForEach(row => row.Delete());
sample test code for linqpad:
void Main()
{
//sample data for test
DataSet ds = new DataSet();
ds.Tables.Add(GetTable1());
ds.Tables.Add(GetTable2());
var result = ( from rec1 in ds.Tables[0].AsEnumerable()
join rec2 in ds.Tables[1].AsEnumerable()
on rec1.Field<string>("FC") equals rec2.Field<string>("FC")
where rec2.Field<int>("Value") == 2 select rec1);
result.ToList().ForEach(row => row.Delete());
//now you have only "ABCD" and "AZY" in table 1
//ds.Tables[0].Dump(); linqpad display result
}
DataTable GetTable1()
{
DataTable table = new DataTable();
table.Columns.Add("FC", typeof(string));
table.Rows.Add("ABCD");
table.Rows.Add("XYZ");
table.Rows.Add("AZY");
return table;
}
DataTable GetTable2()
{
DataTable table = new DataTable();
table.Columns.Add("FC", typeof(string));
table.Columns.Add("Value", typeof(int));
table.Rows.Add("ABCD", 1);
table.Rows.Add("XYZ", 2);
table.Rows.Add("AZY",3);
return table;
}
i created datatables by code and i added those tables to data set . they working fine .but when i pass this dataset to my report i get nothing .here my codes
Dim dt As DataTable = New DAL().selectdatatable(String.Format("SELECT PT.PT_Code, PT.age_sex2, PT.fullname2, Ptsense.PT_Date, DR.Dr_Name, Ptsense.sample, Ptsense.G, Ptsense.coun, Ptsense.comm, Ptsense.organism, Ptsense.lowsens FROM (PT INNER JOIN Ptsense ON PT.PT_Code = Ptsense.PT_Code) INNER JOIN DR ON PT.DR_Code = DR.Dr_Code WHERE PT.PT_Code={0} AND Ptsense.PT_Date=#{1}# AND Ptsense.lowsens <>'{2}'", Txtcode.Text, DateTimePicker1.Value.ToString("dd/MM/yyyy"), ""))
Dim dt3 As DataTable = New DAL().selectdatatable(String.Format("SELECT labdetails.labnme, labdetails.labspecial, labdetails.labadress, labdetails.labphone, labdetails.labtime, labdetails.lablogo,labdetails.labnameenglish,labdetails.labspecialenglish FROM labdetails;"))
Dim dt4 As DataTable = New DAL().selectdatatable(String.Format("SELECT PT.PT_Code, PT.age_sex2, PT.fullname2, Ptsense.PT_Date, DR.Dr_Name, Ptsense.sample, Ptsense.G, Ptsense.coun, Ptsense.comm, Ptsense.organism, Ptsense.lowsens, Ptsense.resis FROM (PT INNER JOIN Ptsense ON PT.PT_Code = Ptsense.PT_Code) INNER JOIN DR ON PT.DR_Code = DR.Dr_Code WHERE PT.PT_Code={0} AND Ptsense.PT_Date=#{1}# AND Ptsense.resis <>'{2}'", Txtcode.Text, DateTimePicker1.Value.ToString("dd/MM/yyyy"), ""))
Dim ds As New DataSet
ds.Tables.AddRange({dt, dt3, dt4})
rprt.SetDataSource(ds)
I am exporting three worked sheet in single XL file. But I am getting a worksheet name like Table1, Table2, Table3.
Below is the C# code for without calling database, working correctly sheet names.
var ds = new DataSet();
var dt = new DataTable("TableName For Sheet1");
dt.Columns.Add("col1");
dt.Columns.Add("col2");
dt.Rows.Add("Value1", "Value2");
var dt2 = new DataTable("TableName For Sheet2");
dt2.Columns.Add("col1");
dt2.Columns.Add("col2");
dt2.Rows.Add("Value1", "Value2");
ds.Tables.Add(dt);
ds.Tables.Add(dt2);
ExcelHelper.ToExcel(ds, "test.xls", Page.Response);
Below is the C# code for calling database stored procedure, but sheet names are given Table1, Table2, Table2.
DataSe ds = new DataSet();
DataTable dt = new DataTable("Registration Details");
DataTable dt1 = new DataTable("Education Details");
DataTable dt2 = new DataTable("Employeement Details");
dt = bl.Get_Registrationdetailsbydate(bo);
gv_Regdetails.DataSource = dt;
gv_Regdetails.DataBind();
dt1 = bl.Get_Registrationdetailsbydate1(bo);
dt2 = bl.Get_Registrationdetailsbydate2(bo);
DataTable filteredEducation = dt1.AsEnumerable()
.Where(x => dt.AsEnumerable()
.Any(z => z.Field<string>("Email").Trim() == x.Field<string>("Email").Trim()))
.CopyToDataTable();
DataTable filteredEmployee = dt2.AsEnumerable()
.Where(x => dt.AsEnumerable()
.Any(z => z.Field<string>("Email").Trim() == x.Field<string>("Email").Trim()))
.CopyToDataTable();
ds.Tables.Add(dt);
ds.Tables.Add(filteredEducation);
ds.Tables.Add(filteredEmployee);
ExcelHelper.ToExcel(ds, "DangoteUsers.xls", Page.Response);
I need sheet names results like Registration Details,Education Details and Employeement Details.
I refer this example: http://www.codeproject.com/Articles/31516/Export-DataSet-to-Multiple-Excel-Sheets
You are overriding dt, dt1 and dt2 after initialization and that is why you are not getting the names correctly and instead you are getting the default name for the tables. Try setting the name for those three tables after assignation or include the table name in the assignation logic. I updated your code to demonstrate this.
DataSet ds = new DataSet();
var dt = bl.Get_Registrationdetailsbydate(bo);
gv_Regdetails.DataSource = dt;
gv_Regdetails.DataBind();
var dt1 = bl.Get_Registrationdetailsbydate1(bo);
var dt2 = bl.Get_Registrationdetailsbydate2(bo);
DataTable filteredEducation = dt1.AsEnumerable()
.Where(x => dt.AsEnumerable()
.Any(z => z.Field<string>("Email").Trim() == x.Field<string>("Email").Trim()))
.CopyToDataTable();
DataTable filteredEmployee = dt2.AsEnumerable()
.Where(x => dt.AsEnumerable()
.Any(z => z.Field<string>("Email").Trim() == x.Field<string>("Email").Trim()))
.CopyToDataTable();
dt.TableName = "Registration Details";
filteredEducation.TableName = "Education Details";
filteredEmployee.TableName = "Employeement Details";
ds.Tables.Add(dt);
ds.Tables.Add(filteredEducation);
ds.Tables.Add(filteredEmployee);
ExcelHelper.ToExcel(ds, "DangoteUsers.xls", Page.Response);
I have 2 Datatable dt and dt2
var dt = MultiCheckCombo3.GetAllChechedBox();
var dt2 =manager.GetAllStudents(student_id, classid);
In the first table dt are two columns "id_staff" and "name_staff"
In the second table are several columns but 2 of them repeat "id_staff" and "name_staff"
I want to create a new DataTable with the fields "id_staff" and "name_staff" common DataTable dt and dt2
how joined these tables?
dt3= dt+dt2
You can use Linq to join the two tables. See the following example.
Code from the article:
var innerGroupJoinQuery =
from category in categories
join prod in products on category.ID equals prod.CategoryID into prodGroup
select new { CategoryName = category.Name, Products = prodGroup };
Have a look at the DataTable.Merge method:
This link from Microsoft has an example of how to do this
If dt and dt2 are DataTables, you can use datatable merge.
DataTable dt3 = dt.Copy()
dt3.Merge(dt2, false, MissingSchemaAction.Ignore)
Maybe something like this:
var dt=new DataTable();
dt.Columns.Add("id_staff",typeof(int));
dt.Columns.Add("name_staff",typeof(string));
var dt2=new DataTable();
dt2.Columns.Add("id_staff",typeof(int));
dt2.Columns.Add("name_staff",typeof(string));
dt.Rows.Add(1,"test");
dt2.Rows.Add(2,"test2");
var result=
(
from datatable1 in dt.AsEnumerable()
select new
{
id_staff=datatable1.Field<int>("id_staff"),
name_staff=datatable1.Field<string>("name_staff")
}
).Concat
(
from datatable2 in dt2.AsEnumerable()
select new
{
id_staff=datatable2.Field<int>("id_staff"),
name_staff=datatable2.Field<string>("name_staff")
}
);