Question

I need to implement column shifting functionality between two data tables. Let say i have columns {A,B,C} in DataTable 1 and {A} in DataTable 2.

If i want to move columns {B,C} to DataTable 2, how can i do this ? The data in both tables should similar.

If DataTable is not a right option , then please help me on how we can achieve this ..

Can this be done with List> - Nested Lists ? Tried below code , but thought merge isn't the right option.

  private void move(DataTable source, DataTable dest, string colname)
    {
        var result = source.AsEnumerable().Select(row => row.Field<string>(colname));
        dest.Columns.Add(colname);
        DataTable dt = source.DefaultView.ToTable(false, colname);

        dest.Merge(dt);          

    }

I'm beginner , so please suggest if there is any other way where we can shift columns based on the user selection.

Was it helpful?

Solution

Sometime back I had done this. I had to manually write the code for data table copy. The method below does the job of copying missing columns from the source table to the target table. It returns the collection of column names that got copied. The second function copies the data from source column to the target column. It takes the primary key column name as input and list of column names for which data has to be copied.

public List<string> CopyDistinctColumns(DataTable source, DataTable target)
{
    var copiedColumn = new List<string>();
    for(var x = 0; x < source.Columns.Count; x++)
    {
        var column = source.Columns[x];
        if(!target.Columns.Contains(column.ColumnName))
        {
            var newCol = new DataColumn
            {
                ColumnName = column.ColumnName,
                DataType = column.DataType,
                Caption = column.Caption,
                DefaultValue = column.DefaultValue,
                MaxLength = column.MaxLength,
            };
            copiedColumn.Add(column.ColumnName);
            target.Columns.Add(newCol);
        }
    }
    return copiedColumn;
}

public void CopyData(DataTable source, DataTable target, string primaryKeyColumnName, List<string> copiedColumns)
{
    for (var i = 0; i < source.Rows.Count; i++)
    {
        var row = source.Rows[i];
        var primaryKeyValue = row[primaryKeyColumnName];
        for (var j = 0; j < target.Rows.Count; j++)
        {
            var trow = target.Rows[j];
            if (trow[primaryKeyColumnName].Equals(primaryKeyValue))
            {
                foreach (var col in copiedColumns)
                {
                    trow[col] = row[col];
                }
                break;
            }
        }
    }
}

OTHER TIPS

check there is copy option for data table, like DataTable dt = new DataTable() dt.copy or dt.clone

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top