Home > front end >  How to avoid looping multiple times in this case?
How to avoid looping multiple times in this case?

Time:10-03

 public Task < Medication > GetMedicationRecord(Guid medicationId) {
 return Task.Factory.StartNew(() => {
     Check.Argument.IsNotEmpty(medicationId, nameof(medicationId));

     var medication = m_MedicationRepository.GetMedications(false, medicationId)
       .FirstOrDefault();

     if (medication == null) {
       //Check see if medication is present in deleted patient medications table
       medication = m_MedicationRepository.GetMedications(true, medicationId)
         .FirstOrDefault();
       if (medication == null)
         return null;
     })
 }

 public string GetMedications(bool isDeletedMedications, Guid medicationId) {
   var query = String.Empty;

   if (!isDeletedMedications)
     query = "something";
   else {
     query = "something else";
   }

   return query;
 }

My query is, In GetMedicationRecord() method I am making a call for repo which calls GetMedications() method two scenarios. 1st scenario is when 1st input parameter is false(isDeletedMedications) and the 2nd scenario is when 1st input parameter is true(isDeletedMedications).

I want to avoid this multiple calling. Is there any attribute or something where i can call GetMedications() method only once.

CodePudding user response:

You essentially want to load all medications, which are all deleted, then all medications which are NOT. Each resulting set is by design different, therefore you are not actually not making more iterations than needed.

But, since the union of non-deleted and deleted medications are all medications, why going through the hastle of having 2 queries at all. Seems like your solution is to remove the isDeletedMedications.

Also yes, it's generally a good idea to build query strings using StringBuilder if they are more than one simple line, and they are constructed base on some logic.

CodePudding user response:

Why don't you add an boolean field isDeleted in your database. When your repository calls to database and receive response:

  • if isDeleted == false, it means your medications were not deleted
  • if isDeleted == true, it means your medications were deleted

So you can remove the parameter bool isDeletedMedications in GetMedications() method

CodePudding user response:

You can directly call the getMedication method without isDeletedMedications parameter and write your query accordingly.

Second way, you can write getMedication method where it will handle null check. I mean first run query for not deleted medication and if it null then run query for deleted medication.

  • Related