Skip to main content
2 of 2
deleted 400 characters in body; edited title
Jamal
  • 35.2k
  • 13
  • 134
  • 238

Getting column values from a datatable

Is there a way I can make the code compact and with fewer ifs?

theData = GetData(); if (theData.Rows.Count > 0) { MyModel = new CustomModel(); dataSetRow = theData.Rows[0]; if (theData.Columns.Contains("Column1")) { if ((!object.ReferenceEquals(dataSetRow["Column1"], DBNull.Value))) { MyModel.Column1 = Convert.ToString(dataSetRow["Column1"]); } } if (theData.Columns.Contains("Column2")) { if ((!object.ReferenceEquals(dataSetRow["Column2"], DBNull.Value))) { MyModel.Column2 = Convert.ToString(dataSetRow["Column2"]); } } if (theData.Columns.Contains("Column3")) { if ((!object.ReferenceEquals(dataSetRow["Column3"], DBNull.Value))) { MyModel.Column3 = Convert.ToString(dataSetRow["Column3"]); } } if (theData.Columns.Contains("Column4")) { if ((!object.ReferenceEquals(dataSetRow["Column4"], DBNull.Value))) { MyModel.Column4 = Convert.ToString(dataSetRow["Column4"]); } } 
Simsons
  • 723
  • 1
  • 8
  • 17