使用LINQ创建数据表以选择多个列

时间:2019-06-06 14:02:52

标签: c# linq datatable

我需要从另一个拥有但只有一些列(完全相同的行)的数据表中创建一个数据表。

是否有使用LINQ做到这一点的简单方法?

我尝试过:

DataTable dataCopy = dt.AsEnumerable()
                       .Select(r => new { A = r.Field<string>("Column A"),
                                          B = r.Field<string>("Column B") });

但是它没有“ CopyToDataTable”方法。

我正在寻找实现这一目标的最佳性能方法,因为我的“源”数据表非常庞大!

3 个答案:

答案 0 :(得分:1)

您可以简单地使用[HttpPost] public ActionResult AgregarArticulos(ArticuloModel articulo) { ArticulosSele MisArticulos = new ArticulosSele(); List<ArticulosSele> ListaArticulosFactura = new List<ArticulosSele>(); dbModels dbArtFact = new dbModels(); ListaArticulosFactura = dbArtFact.ArticulosSele.ToList(); var Seleccionados = articulo.Articulos.Where(x => x.IsChecked == true).ToList<Articulos>(); int tamaño = Seleccionados.Count();//Obtenemos el tamaño de la lista for (int i= 0; i< tamaño; i++) { //MisArticulos.foliofactura = idfact; int cod= (int)Seleccionados[i].codigo; //"MisArticulos.codigo" gives me 0, but "cod" has a value. MisArticulos.codigo = cod; MisArticulos.nombre = Seleccionados[i].nombre;//the same problem here } } 复制dataTable并从复制的对象中删除不需要的列。

dataTable.Copy()

答案 1 :(得分:0)

    Stopwatch time = new Stopwatch();

                time.Start();
    //COMPARE YOUR CODE (.Copy, Clone or Develop yourself)
                DataTable dtTarget = dtSource.CopyDataTable(new List<string>() { "A", "B" });

                foreach (DataColumn column in dtTarget.Columns)
                {
                    Console.WriteLine("ColumnName : {0}", column.ColumnName);

                    foreach (DataRow row in dtTarget.Rows)
                    {
                        Console.WriteLine("Rows : {0}", row[column.ColumnName]);
                    }
                }

                time.Stop();

                Console.WriteLine("{0}", time.Elapsed);



public static class DataTableHelper
    {
        public static DataTable CopyDataTable(
           this DataTable dtSource,
            List<string> columnsName)
        {

            DataTable dtTarget = new DataTable();
            if (dtSource.Columns.Count > 0)
            {

                foreach (DataColumn columnSource in dtSource.Columns)
                {
                    var columnTargetMapped = columnsName.FirstOrDefault(c => c == columnSource.ColumnName);

                    if(columnTargetMapped == null)
                    {
                        continue;
                    }

                    dtTarget.Columns.Add(columnTargetMapped);

                    foreach (DataRow drSource in dtSource.Rows)
                    {
                        var valueColumn = drSource[columnSource];

                        DataRow drTarget = dtTarget.NewRow();

                        drTarget[columnTargetMapped] = valueColumn;

                        dtTarget.Rows.Add(drTarget);
                    }
                }
            }

            return dtTarget;
        }

答案 2 :(得分:0)

    public static DataTable GetDataTablePart(this DataTable dt, params string[] ColumnNames)
    {
        var dtPart = new DataTable("TablePart");
        var Names = new List<DataColumn>();
        foreach (DataColumn Column in dt.Columns)
        {
            if(ColumnNames.Contains(Column.ColumnName))
            {
                Names.Add(Column);
            }
        }
        dtPart.Columns.AddRange(Names.ToArray());
        foreach(DataRow row in dt.Rows)
        {
            var NewRow = new object[Names.Count()];
            var i = 0;
            foreach (var Name in Names)
            {
                NewRow[i] = row[Name];
                i = i + 1;
            }
            dtPart.LoadDataRow(NewRow, false);
        }
        return dtPart;
    }

linq版本。...

    public static DataTable GetDataTablePart(this DataTable dt, params string[] ColumnNames)
    {
        var RowCount = 0;
        var dtPart = new DataTable("TablePart");
        dtPart.Columns.AddRange((from column in dt.Columns.Cast<DataColumn>()
                     where ColumnNames.Contains(column.ColumnName)
                     select column).ToArray());
        return (from row in dt.AsEnumerable()
                  let rowCount = RowCount = dt.Rows.Count
                  let RowValues = (from column in dtPart.Columns.Cast<DataColumn>()
                                   select row[column]).ToArray()
                  let decCount = RowCount = RowCount - 1
                  where dtPart.LoadDataRow(RowValues,LoadOption.OverwriteChanges) != default && decCount > 0
                  select dtPart).FirstOrDefault();
    }