TryFindRowByPrimaryKey Method

Overview

The TryFindRowByPrimaryKey extension method searches a table for a row whose primary key column(s) match specified value(s).

It performs a linear scan of dataTable.Rows and supports both single-column and composite primary keys.

Declaration

/// <summary>
/// Tries to find a row by primary key values by scanning table rows.
/// Works for single or composite primary keys.
/// </summary>
public static bool TryFindRowByPrimaryKey(this IDataTable? dataTable, List<string> primaryKeyColumnNames, object?[] primaryKeyValues, out IDataRow? foundRow)

/// <summary>
/// Convenience overload for single-column primary keys.
/// </summary>
public static bool TryFindRowByPrimaryKey(this IDataTable? dataTable, string primaryKeyColumnName, object? primaryKeyValue, out IDataRow? foundRow)

Namespace and Assembly

Namespace: PocoDataSet.Extensions
Assembly: PocoDataSet.Extensions.dll

Behavior

Usage Example

using PocoDataSet.Data;
using PocoDataSet.Extensions;
using PocoDataSet.IData;

DataTable table = new DataTable();
table.TableName = "Employee";
table.AddColumn("Id", "Int32", isNullable: false, isPrimaryKey: true);
table.AddColumn("Name", "String");

var r1 = table.AddNewRow();
r1["Id"] = 1;
r1["Name"] = "Ada";
r1.AcceptChanges();

var r2 = table.AddNewRow();
r2["Id"] = 2;
r2["Name"] = "Alan";
r2.AcceptChanges();

IDataRow? found;
bool ok = table.TryFindRowByPrimaryKey("Id", 2, out found);
if (ok)
{
// found["Name"] == "Alan"
}

// Composite key example:
// List<string> pk = new List<string> { "TenantId", "EmployeeId" };
// object?[] values = new object?[] { 10, 2 };
// table.TryFindRowByPrimaryKey(pk, values, out found);

Notes

This method performs a linear scan. For frequent lookups on large tables, consider building an index (for example, by using your BuildPrimaryKeyIndex extension where appropriate).

If primary key values may differ in type (e.g., int vs long), normalize your input values before calling, because comparison uses Equals.

 

Table of Content POCO DataSet DataTable Extensions Group DataTable Members

 


Business Process Programming in .Net
© 2004–2026 Laskarzhevsky Software Inc.
Unless otherwise noted, the content of this website is licensed under the Creative Commons Attribution 4.0 International License (CC BY 4.0).
Code examples are provided under the MIT License.
You are free to share and adapt the material provided that appropriate credit is given and any modifications are clearly indicated.
The information provided on this website is for educational purposes only.
The author and publisher make no warranties regarding the completeness or suitability of the information and are not responsible for any damages resulting from its use.