To compare two DataTables and return the unmatched rows, you can use LINQ in C#. LINQ provides a powerful way to query data and perform set operations like finding the differences between two collections. Here's an example of how to compare two DataTables and return the rows that are present in one DataTable but not in the other:

Assuming you have two DataTables named table1 and table2, and both have the same schema (same columns):

csharp
using System; using System.Data; using System.Linq; public class Program { public static void Main() { // Sample DataTables DataTable table1 = GetSampleDataTable1(); DataTable table2 = GetSampleDataTable2(); // Compare DataTables and get unmatched rows from table1 DataTable unmatchedRows = GetUnmatchedRows(table1, table2); // Print unmatched rows PrintDataTable(unmatchedRows); } // Sample DataTable 1 private static DataTable GetSampleDataTable1() { DataTable table = new DataTable(); table.Columns.Add("ID", typeof(int)); table.Columns.Add("Name", typeof(string)); table.Rows.Add(1, "John"); table.Rows.Add(2, "Alice"); table.Rows.Add(3, "Bob"); return table; } // Sample DataTable 2 private static DataTable GetSampleDataTable2() { DataTable table = new DataTable(); table.Columns.Add("ID", typeof(int)); table.Columns.Add("Name", typeof(string)); table.Rows.Add(1, "John"); table.Rows.Add(3, "Bob"); table.Rows.Add(4, "Eve"); return table; } // Compare DataTables and get unmatched rows from table1 private static DataTable GetUnmatchedRows(DataTable table1, DataTable table2) { // LINQ query to get unmatched rows from table1 var unmatchedRows = table1.AsEnumerable() .Where(row1 => !table2.AsEnumerable().Any(row2 => row1.ItemArray.SequenceEqual(row2.ItemArray))) .CopyToDataTable(); return unmatchedRows; } // Print DataTable private static void PrintDataTable(DataTable table) { foreach (DataRow row in table.Rows) { foreach (var item in row.ItemArray) { Console.Write(item + " "); } Console.WriteLine(); } } }

In this example, we have two sample DataTables table1 and table2. We compare them using LINQ's Any and SequenceEqual methods to find the unmatched rows in table1. The result is then stored in the unmatchedRows DataTable, which contains the rows that are present in table1 but not in table2. The PrintDataTable method is used to print the unmatched rows.

Have questions or queries?
Get in Touch