简体   繁体   中英

Convert LINQ to DataTable

The linq query is returning result in form of {DataRow Job1, DataRow Run} . How can i convert JoinResult into a DataTable .

var JoinResult = (from Job1 in Jobdata.AsEnumerable()
                  join Product in Productdata.AsEnumerable()
                  on Job1.Field<int>("Job_Id") equals Product.Field<int>("Job_Id")
                  join Run in data.AsEnumerable()
                  on Job1.Field<int>("Run_Id") equals Run.Field<int>("Run_Id")
                  select new { Job1, Run });

You can create a new datatable by looping trough the query result:

private DataTable createDt()
{
    var JoinResult = (from Job1 in Jobdata.AsEnumerable()
                      join Product in Productdata.AsEnumerable()
                      on Job1.Field<int>("Job_Id") equals Product.Field<int>("Job_Id")
                      join Run in data.AsEnumerable()
                      on Job1.Field<int>("Run_Id") equals Run.Field<int>("Run_Id")
                      select new { Job1, Run });

    DataTable newdt = new DataTable();

    // declare strongly typed data columns
    DataColumn run = new DataColumn("run");
    run.DataType = System.Type.GetType("System.Int32");
    newdt.Columns.Add(run);

    DataColumn job1 = new DataColumn("job1");
    job1.DataType = System.Type.GetType("System.Int32");
    newdt.Columns.Add(job1);


    foreach (var x in JoinResult)
    {
        DataRow dr = newdt.NewRow();
        dr["run"] = x.Run;
        dr["job1"] = x.Job1;
        newdt.Rows.Add(dr);
    }

    return newdt;
}

BTW - you can not use CopyToDataTable() in your case: Why am I not getting .CopyToDataTable() in Linq Query()

but if you insist to use it: How to: Implement CopyToDataTable Where the Generic Type T Is Not a DataRow

You can create an extension method & use it like below:

    /// <Summary>
    /// Convert a IEnumerable to a DataTable.
    /// <TypeParam name="T">Type representing the type to convert.</TypeParam>
    /// <param name="source">List of requested type representing the values to convert.</param>
    /// <returns> returns a DataTable</returns>
    /// </Summary>
    public static DataTable ToDataTable<T>(this IEnumerable<T> source)
    {
        // Use reflection to get the properties for the type we’re converting to a DataTable.
        var props = typeof(T).GetProperties();

        // Build the structure of the DataTable by converting the PropertyInfo[] into DataColumn[] using property list
        // Add each DataColumn to the DataTable at one time with the AddRange method.
        var dt = new DataTable();
        dt.Columns.AddRange(
          props.Select(p => new DataColumn(p.Name, BaseType(p.PropertyType))).ToArray());

        // Populate the property values to the DataTable
        source.ToList().ForEach(
          i => dt.Rows.Add(props.Select(p => p.GetValue(i, null)).ToArray())
        );

        return dt;
    }


//To call the above method:
var dt = JoinResult.ToDataTable();

Note: You just need to update your linq query to get IEnumerable data. Hope it helps you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM