【问题标题】:Convert LINQ to DataTable将 LINQ 转换为数据表
【发布时间】:2017-11-25 15:35:29
【问题描述】:

linq 查询以 {DataRow Job1, DataRow Run} 的形式返回结果。如何将JoinResult 转换为 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 });

【问题讨论】:

  • 不清楚(比如JobdataProduct有数据表关系,为什么不使用常规数据表解决方案?)和广泛。您是否在寻找现有的解决方案?这并不是一个新问题。
  • 所以你想要一个DataTable,每个数据行的列并排?

标签: c# linq datatable


【解决方案1】:

您可以创建一个扩展方法并像下面这样使用它:

    /// <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();

注意:您只需更新 linq 查询即可获取 IEnumerable 数据。 希望对你有帮助。

【讨论】:

    【解决方案2】:

    您可以通过循环遍历查询结果来创建一个新的datatable

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

    顺便说一句 - 你不能在你的情况下使用CopyToDataTable()Why am I not getting .CopyToDataTable() in Linq Query()

    但如果你坚持使用它: How to: Implement CopyToDataTable Where the Generic Type T Is Not a DataRow

    【讨论】:

    猜你喜欢
    • 2011-01-15
    • 1970-01-01
    • 2012-05-04
    • 1970-01-01
    • 2011-11-12
    • 1970-01-01
    • 2018-12-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多