Convert Boolean Columns
Converts columns in a DataTable that contain only Boolean-compatible values into actual Boolean type columns.
- Columns are considered Boolean-compatible if all values are “true”, “false”, “1”, or “0” (case insensitive)
- For each compatible column, a new Boolean column is created and populated with the corresponding True/False value
- The original column is then removed and replaced with the new Boolean column under the original name
- Conversion is done in-place; the input DataTable is modified directly
VB
Public Sub ConvertBooleanColumns(ByRef dt As DataTable)
Dim columnsToConvert As New List(Of String)
' Step 1: Identify columns that contain only boolean-compatible values
For Each col As DataColumn In dt.Columns
Dim isBooleanCandidate As Boolean = True
For Each row As DataRow In dt.Rows
Dim value As String = row(col.ColumnName).ToString().Trim().ToLower()
If value <> "true" AndAlso value <> "false" AndAlso value <> "0" AndAlso value <> "1" Then
isBooleanCandidate = False
Exit For
End If
Next
If isBooleanCandidate Then
columnsToConvert.Add(col.ColumnName)
End If
Next
' Step 2: Create new Boolean columns and replace the originals
For Each colName As String In columnsToConvert
Dim newColName As String = colName & "_bool"
dt.Columns.Add(newColName, GetType(Boolean))
For Each row As DataRow In dt.Rows
Dim value As String = row(colName).ToString().Trim().ToLower()
row(newColName) = (value = "1" OrElse value = "true")
Next
' Remove the original column and rename the new one
dt.Columns.Remove(colName)
dt.Columns(newColName).ColumnName = colName
Next
End Sub