Home > Net >  How to reduce a if statements?
How to reduce a if statements?

Time:10-29

I have a object that has the result of a query, this object has date´s fields and i need to deal where the field has the date '01-01-1991'change to null. How can i simplify this if statement?

if(item.date01 == '01-01-1991')
   item.date01 = null;

if(item.date02 == '01-01-1991')
   item.date02 = null;

if(item.date03 == '01-01-1991')
   item.date03 = null;

if(item.date04 == '01-01-1991')
   item.date04 = null;

i tried to use foreach, but i didnt know how...

foreach(var item in itens)
{
    if(item.obj == '01-01-1991')
      item.obj = null;
}

CodePudding user response:

I'm not sure if you have a working example, since the single quotes in `'01-01-1991' are not valid to use in a string or datetime.

Also, you mention that the date01, date02, ... are fields. In that case, you can do the following:

var item = new DataItem();

void CheckAndSet(ref string? date)
{
    if (date == "01-01-1900")
    {
        date = null;
    }
}

CheckAndSet(ref item.date01);
CheckAndSet(ref item.date02);
CheckAndSet(ref item.date03);
CheckAndSet(ref item.date04);

public class DataItem
{
    public string? date01;
    public string? date02;
    public string? date03;
    public string? date04;
}

To elaborate, you can use the ref keyword to keep the reference to the original variable, which in this case is the date0x field in the DataItem class.

CodePudding user response:

iterate each item of items

foreach(var item in items)
{
    this.CheckAndSetDate(ref item.date01,"01-01-1991");
    this.CheckAndSetDate(ref item.date02,"01-01-1991");
    this.CheckAndSetDate(ref item.date03,"01-01-1991");
    this.CheckAndSetDate(ref item.date04,"01-01-1991");
}

then create validate function

public void CheckAndSetDate(ref string date, string value)
{
   date = date == value ? null : date;
}

or

foreach(var item in items)
{
    item.date01 = this.CheckAndSetDate(item.date01,"01-01-1991");
    item.date02 = this.CheckAndSetDate(item.date02,"01-01-1991");
    item.date03 = this.CheckAndSetDate(item.date03,"01-01-1991");
    item.date04 = this.CheckAndSetDate(item.date04,"01-01-1991");
}

public stringCheckAndSetDate(ref string date, string value)
{
   return date == value ? null : date;
}

CodePudding user response:

You can use Reflection.

foreach(var element in (IEnumerable)item)
     {
          Type type = element.GetType();
          PropertyInfo[] properties = type.GetProperties();
          foreach(PropertyInfo p in properties)
          {
              if(p.GetValue(element,null) == "01-01-1991")
              {
                  p.SetValue(item, null, null)
              }

           } 
      }
  • Related