没有在Xamarin中获得列表模型中的最后一项

时间:2018-08-27 16:50:11

标签: arrays json visual-studio xamarin xamarin.forms

我正在将此方法与下面的列表一起使用,以检索模型中Jason的项目列表

   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;          

        } 

List<ResturentPair>是食品的集合,其中方法从项目1返回到末尾,但方法总是返回少于集合中项目数的1个项目,例如说List<ResturentPair>包含10个项目,它仅返回9,是for循环或变量i的问题,将不胜感激,在此先感谢您的支持

1 个答案:

答案 0 :(得分:1)

关键是:

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

代替

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

您应该对您的逻辑部分区域进行测试,只需简单地通过使用

进行报告即可
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