I assume i already a variable where there is a column number which will be IMEI if one is available. If this is not the case, see End of answer.
You cannot use the if in an object initializer. What you can do is split it into a separate statement:
while (rd.Read()) { var device = new DeviceModlInfo { ID = rd.GetGuid("ID"), Manufacturer = new Manufacturer() { ID = rd.GetGuid("ManufacturerID"), Name = rd.GetString("ManufacturerName"), ManufacturerType (ManufacturerEnum)rd.GetInt32("ManufecturerType") }, Model = rd.GetString("Model"); }; if (rd.GetName(i).Equals("IMEI", StringComparison.InvariantCultureIgnoreCase)) { device.IMEI = rd.GetString("IMEI"); } list.Add(device); }
Alternatively, you can use the conditional ?: operator to assign a single value or IMEI value based on a condition:
while (rd.Read()) { list.Add(new DeviceModelInfo { ID = rd.GetGuid("ID"), Manufacturer = new Manufacturer() { ID = rd.GetGuid("ManufacturerID"), Name = rd.GetString("ManufacturerName"), ManufacturerType (ManufacturerEnum)rd.GetInt32("ManufecturerType") }, Model = rd.GetString("Model"), IMEI = rd.GetName(i).Equals("IMEI", StringComparison.InvariantCultureIgnoreCase)) ? rd.GetString("IMEI") : null; });
}
If you really don't know which column will be IMEI, I would probably write a separate method to check if a column is present or not, only once. Then you write (outside the loop):
int? imeiColumn = GetColumn(dr, "IMEI");
Then in the initializer of the object write:
IMEI = imeiColumn != null ? dr.GetString(imeiColumn.Value) : null
Where GetColumn might look something like this:
static int? GetColumn(DbDataReader reader, string name) { for (int i = 0; i < reader.VisibleFieldCount; i++) { if (reader.GetName(i).Equals(name, StringComparison.InvariantCultureIgnoreCase)) { return i; } } return null; }