Home > Software design >  What is best replacement for a "foreach" loop that is executed only once?
What is best replacement for a "foreach" loop that is executed only once?

Time:09-28

I am trying to refactor my code, my for each loop doesn't make much sense to use due to it being executed only once.

My question is, would it be best to replace it with an if statement, or is there a better way to do it?

int minReportNo = 0;

if (ValueUtil.IsNull(parentRow) || tableName == CompResultHeadEntity.EntityTableName)
{
    foreach (CompResultHeadEntity header in dc.SelectEntities<CompResultHeadEntity>("", CompResultHeadEntity.ReportnoCol))
    {
        minReportNo = header.Reportno;
        break;
    }

    if (minReportNo > 0)
        minReportNo = 0;
}

So instead of using:

foreach (CompResultHeadEntity header in dc.SelectEntities<CompResultHeadEntity>("", CompResultHeadEntity.ReportnoCol))

should I use:

if(CompResultHeadEntity header in dc.SelectEntities<CompResultHeadEntity>("", CompResultHeadEntity.ReportnoCol))

CodePudding user response:

 int minReportNo = 0;
        if (ValueUtil.IsNull(parentRow) || tableName == CompResultHeadEntity.EntityTableName)
        {
            var result = dc.SelectEntities<CompResultHeadEntity>("", CompResultHeadEntity.ReportnoCol).FirstOrDefault();
            if(result != null)
                minReportNo = header.Reportno;
            if (minReportNo > 0) 
                minReportNo = 0;
        }

CodePudding user response:

You can replace your foreach loop with linq expression:

minReportNo = dc.SelectEntities<CompResultHeadEntity>(string.Empty, CompResultHeadEntity.ReportnoCol)?.FirstOrDefault()?.Reportno ?? minReportNo;

In case there's guarantee that there's always one non null element in the collection, linq expression can be simplified:

 minReportNo = dc.SelectEntities<CompResultHeadEntity>(string.Empty, CompResultHeadEntity.ReportnoCol).First().Reportno;

Add the following namespace for linq to work.

using System.Linq;

P.S. I've also replaced your "" with string.Empty :)

P.P.S. I've just noticed that Camilo posted this same exact answer as a comment. Shout out to him

  •  Tags:  
  • c#
  • Related