signalover
signalover

Reputation: 167

Search for an object within an Array with a loop

I have an array of objects of my class:

HumorDiary[] note = JsonConvert.DeserializeObject<HumorDiary[]>(textt);

and I would like to look for an object inside it whose int Giorno property is equal to DateTime.Now.Day.

Here comes my doubt. If it doesn't find any objects, I would like it to increase DateTime.Now.Day by 1 and continually compare it to the Giorno property among the objects in the Array, as long as it doesn't find an object

foreach (HumorDiary diario in note)
{
    if (diario.Anno == DateTime.Now.Year)
    {                        
        if(diario.Giorno == DateTime.Now.Day)
        {
            HumorDiary hd = note.First();                                         
        }  
        else .........                       
    }               
}

Upvotes: 0

Views: 58

Answers (2)

atiyar
atiyar

Reputation: 8305

Currently, you are declaring a HumorDiary variable inside the loop when you find a match, and trying to store a reference in it. But once the loop is complete, that variable will no longer exist and you will loose the reference.

Declare the HumorDiary variable outside the loop. Then inside the loop, if you find a match, store the reference in that variable, and break out of the loop. Else increase your intended value and continue with the loop -

HumorDiary[] note = JsonConvert.DeserializeObject<HumorDiary[]>(textt);

HumorDiary diary = null;

foreach (HumorDiary diario in note)
{
    if (diario.Anno == DateTime.Now.Year)
    {                        
        if(diario.Giorno == DateTime.Now.Day)
        {
            diary = diario;
            break;
        }
        else
        {
            diario.Giorno++;
        }
    }
}

EDIT :
If by "I would like it to increase DateTime.Now.Day by 1" you meant to increase a value of a separate counter, and not the value of Giorno, then keep a counter outside the loop initialized with DateTime.Now.Day -

int count = DateTime.Now.Day;

then in the else block increase it's value -

else
{
    count++;
}        

Upvotes: 1

Jason
Jason

Reputation: 89127

use a while loop

HumorDiary hd = null;

var date = DateTime.Now.Day;

while(hd == null)
{
  foreach(...)

  if (hd == null) {
    date++;
  }
}

Upvotes: 0

Related Questions