Home > Blockchain >  DataTable in C# - named rows
DataTable in C# - named rows

Time:05-09

Is it possible to give name for each row in DataTable? I would like to simply refer to the given cell in DataTable by typing

myDataTable.Rows["Row1"]["Column1"]

instead passing Row Index as int.

CodePudding user response:

You can't do this, because rows are only indexed by their row index. Columns are indexed by their column index and column name. If you need to reference rows by a name, you must create your own index:

var rowNameToIndexMap = new Dictionary<string, int>();
var dataTable = new DataTable();
      
/* Index a row */
var row = dataTable.NewRow();
dataTable.Rows.Add(row);
var rowName = "first row";
rowNameToIndexMap.Add(rowName, dataTable.Rows.Count - 1);

/* Retrieve first row by its row name */
if (rowNameToIndexMap.TryGetValue(rowName, out int rowIndex))
{
  var firstRow = dataTable.Rows[rowIndex];
}
  •  Tags:  
  • c#
  • Related