Worth pointing out that Contains(...) and IndexOf(...) >= 0 are both case-insensitive.
Good advise is to disallow multiple columns having the same name which differ only by case! But if you do, then Contains displays some odd behaviour:
// In all tests below, "IndexOf(...) >= 0" gives the same result
DataTable dt1 = new DataTable();
dt1.Columns.Add("Test");
dt1.Columns.Contains("Test"); // true, and same result with "IndexOf >= 0"
dt1.Columns.Contains("test"); // true...surprise!
dt1.Columns.Contains("TEST"); // true...surprise again!
DataTable dt2 = new DataTable();
dt2.Columns.Add("Test");
dt2.Columns.Add("test"); // works, but not recommended!
// Note: Adding a 2nd column with the same case, i.e. "Test", is not allowed
dt2.Columns.Contains("test"); // true
dt2.Columns.Contains("Test"); // true
dt2.Columns.Contains("TEST"); // false...huh?
The performance profile of Contains is also strange. Both dt1.Columns.Contains("Test"); and dt1.Columns.Contains("test"); return TRUE. Careful timing shows that when the column name exists with the same case, Contains is super-fast, almost like HashSet::Contains. But when the column name exists with different case (e.g. "test"), the performance is much slower, almost like every column is checked...and then the return is TRUE anyway!
These odd behaviours appear to be a feature of DataTable::Columns::Contains. If you need explicit case-sensitivity, or to get more consistent behaviour where you may have column names differing only by case, consider:
private bool ContainsCaseSensitive(DataTable dt, string colName)
{
foreach (DataColumn col in dt.Columns)
{
if (col.ColumnName.Equals(colName))
return true;
}
return false;
}
The performance of ContainsCaseSensitive is similar to Contains when the column you are searching for has a low Ordinal position, or does not exist, in the DataTable. For columns with a high Ordinal position, then ContainsCaseSensitive is a bit slower than Contains or IndexOf >= 0.