2011-10-15 31 views
6

Tengo dos tablas de datos de la siguiente maneraLa fusión de dos tablas de datos en C#

Table1 
-------------------------------- 
Id  | Batch | Qty 
----------------------------- 
1   A1  5 
2   A2  5 
3   A3  5 
4   A4  5 


Table2 
-------------------------------- 
Id  | Batch | Qty 
----------------------------- 
1   A1  6 
2   A2  6 
3   A3  6 
5   A5  10 

Expected result 
-------------------------------- 
Id  | Batch | Qty 
----------------------------- 
1   A1  6 (Qty updated) 
2   A2  6 (Qty updated) 
3   A3  6 (Qty updated) 
4   A4  5 (remains as same) 
5   A5  10 (row in table 2) 

¿Cómo puedo lograr esto en C#. Si alguien conoce esta operación tabla de datos por favor, comparta ..

+0

Si hay una coincidencia de identificación de lote y en ambas tablas, ¿Quieres el valor de mayor cantidad, o simplemente el valor de la tabla 2? – Tim

+0

@Tim: desea actualizar el valor de la tabla 2 – Nithesh

+0

¿Qué versión de C#? ¿Estás usando 'DataTable' como en la clase' DataTable'? ¿Estás usando la versión genérica? (como en Typed DataSet/DataTable)? – xanatos

Respuesta

5

intentar algo como esto, este es un ejemplo de cómo combinar dos tablas de datos ...

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 

using System.Data; 

namespace ConsoleApplication1 
{ 
    class Program 
    { 
    static void Main(string[] args) 
    { 
      DataColumn col; 
      DataTable table1 = new DataTable(); 
      table1.PrimaryKey = new DataColumn[] { 
      col = table1.Columns.Add("slot_id") 
      }; 
      col.DataType = typeof(int); 
      col.Unique = true; 
      col = table1.Columns.Add("appointment_time"); 
      col = table1.Columns.Add("patient_name"); 
      col = table1.Columns.Add("patient_doctor"); 

      table1.Rows.Add(1, "0900", "George Michael"); 

      DataTable table2 = new DataTable(); 
      table2.PrimaryKey = new DataColumn[] { 
      col = table2.Columns.Add("slot_id") 
      }; 
      col.DataType = typeof(int); 
      col.Unique = true; 
     col = table2.Columns.Add("appointment_time"); 

      table2.Rows.Add(1, "0900"); 
      table2.Rows.Add(2, "1000"); 
      table2.Rows.Add(3, "1100"); 
      table2.Rows.Add(4, "1200"); 

     DataTable merged = new DataTable(); 
     merged.Merge(table1); 
     merged.Merge(table2); 

     foreach (DataColumn dc in merged.Columns) 
     Console.Write(dc.ColumnName + "\t"); 
     Console.WriteLine(); 

     foreach (DataRow dr in merged.Rows) 
     { 
      foreach (DataColumn dc in merged.Columns) 
      Console.Write(dr[dc.ColumnName] + "\t"); 
      Console.WriteLine(); 
     } 
     Console.WriteLine(); 

     Console.Write("Press any key to continue . . . "); 
     Console.ReadKey(true); 
     Console.WriteLine(); 
    } 
    } 
} 
+0

gracias errorstacks esto es lo que estoy buscando – Nithesh

+0

de nada ...... –

Cuestiones relacionadas