insert datarow in datatable if unique on multiple columns in csharp

To insert a DataRow in a DataTable only if it's unique on multiple columns in C#, you can use the DataTable.Select() method to search for the matching rows before adding the new row. Here's an example code snippet:

main.cs
// Create a new DataTable
DataTable dataTable = new DataTable();

// Add columns to the DataTable
dataTable.Columns.Add("Column1", typeof(string));
dataTable.Columns.Add("Column2", typeof(int));
dataTable.Columns.Add("Column3", typeof(decimal));

// Create a new DataRow
DataRow newRow = dataTable.NewRow();
newRow["Column1"] = "Value1";
newRow["Column2"] = 123;
newRow["Column3"] = 45.67m;

// Check if the row is unique on columns "Column1" and "Column2"
DataRow[] foundRows = dataTable.Select("Column1 = 'Value1' AND Column2 = 123");

if (foundRows.Length == 0) // no matching rows found, insert the new row
{
    dataTable.Rows.Add(newRow);
}
647 chars
22 lines

In this example, the Select() method searches for rows that match the values "Value1" and 123 in columns "Column1" and "Column2", respectively. If no matching rows are found, the new DataRow is added to the DataTable.

gistlibby LogSnag