Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If/Else in Inline Synatx to declase class object with properties C#

Tags:

I have requirement to dynamically add property values based on column values. Current I am creating object as below:

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.GetString("IMEI")
    });
 }

But I need to check if IMEI column is available or not in DataReader but when I am using if else then its giving syntax error I want to add IMEI if its available in DataReader how can I achieve that?

 if (rd.GetName(i).Equals("IMEI", StringComparison.InvariantCultureIgnoreCase))
    IMEI = rd.GetString("IMEI")
like image 707
Pankaj Bhatia Avatar asked Apr 03 '18 05:04

Pankaj Bhatia


People also ask

How do you declare a property in a classroom?

A property inside a class can be declared as abstract by using the keyword abstract. Remember that an abstract property in a class carries no code at all.

How do you declare a property?

To declare properties, add a static properties getter to the element's class. The getter should return an object containing property declarations. Attribute type, used for deserializing from an attribute. Polymer supports deserializing the following types: Boolean , Date , Number , String , Array and Object .

Why we use get set property in C#?

A get property accessor is used to return the property value, and a set property accessor is used to assign a new value. In C# 9 and later, an init property accessor is used to assign a new value only during object construction. These accessors can have different access levels.

What is property explain read/write property with proper syntax and example?

The Read-Write Property is used for both reading the data from the data field as well as writing the data into the data field of a class. This property will contain two accessors i.e. set and get. The set accessor is used to set or write the value to a data field and the get accessor is read the data from a variable.


2 Answers

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;
}
like image 128
Jon Skeet Avatar answered Sep 22 '22 12:09

Jon Skeet


You can use this extension method:

public static bool ColumnExists(this IDataRecord dr, string ColumnName)
{
    for (int i=0; i < dr.FieldCount; i++)
    {
        if (dr.GetName(i).Equals(ColumnName, StringComparison.InvariantCultureIgnoreCase))
            return true;
    }
    return false;
}

Use:

while (rd.Read())
{
    if(rd.ColumnExists("IMEI"))
    // DO YOUR WORK
}

Another way using LINQ:

Only work with .NET 3.5 and above

 while (rd.Read())
 {
     if(Enumerable.Range(0, rd.FieldCount).Any(c => rd.GetName(c) == "IMEI"))
     // DO YOUR WORK
 }
like image 36
Gaurang Dave Avatar answered Sep 22 '22 12:09

Gaurang Dave