Pan Weerasekara
Pan Weerasekara

Reputation: 85

Not getting the last item in the list model in xamarin

i am using this method with the list as below to retrieve the Jason list of items in the model

   private List<ResturentPair> GetDishItems(List<Resturent> list)
        {
            var res = new List<ResturentPair>();           
            for (int i = 0; i < list.Count ; i++)
            {
                res.Add(new ResturentPair {Item1 = (i < list.Count - 1 ? list[i] : null) , Item2 = ((i < list.Count - 1 && i + 1 < list.Count - 1 )? list[i+1] : null) , Item3 = ((i < list.Count - 1 && i + 2 < list.Count - 1  )? list[i+2] : null)});               

                i = i + 2;              
            }
            return res;          

        } 

the List<ResturentPair> is collection of food items where the method returns from item 1 to the end but always the method returns with 1 item less than the number of items in the collection , for example say List<ResturentPair> contains items of 10 , it returns only 9 , is that the issue with the for loop or the variable i, help will be appreciated, Thank you in advance for the support

Upvotes: 0

Views: 56

Answers (1)

Leo Vun
Leo Vun

Reputation: 36

the key is that:

Item1 = (i <= list.Count - 1 ? list[i] : null) 

instead of

Item1 = (i < list.Count - 1 ? list[i] : null)

You should do a test for you logic part area, just simply report by using

var firstLogic = (i < list.Count - 1 ? list[i] : null) ;
var secondLogic = i < list.Count - 1 && i + 1 < list.Count - 1;
var thirdLogic = i < list.Count - 1 && i + 2 < list.Count - 1;

First loop Second loop

Upvotes: 1

Related Questions