I'm assuming i
is already a variable somewhere which has the number of the column that will be the IMEI if it's available. If that's not the case, see the end of the answer.
You can't use an if
statement in an object initializer. What you could do is separate it out 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 could use the conditional ?: operator to assign one value or another to IMEI
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 actually don't know which column would be the IMEI, I'd probably write a separate method to check whether the column is present or not, just once. You'd then write (outside the loop):
int? imeiColumn = GetColumn(dr, "IMEI");
Then in your object initializer, write:
IMEI = imeiColumn != null ? dr.GetString(imeiColumn.Value) : null
Where GetColumn
might look something like:
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;
}