Member 13921752 Ответов: 1

Индекс был вне досягаемости. Должно быть неотрицательным и меньше размера имени параметра коллекции:index


У меня есть список элементов контекста, и когда я пишу yestarday>сегодня появляется ошибка
"
Index was out of range. Must be non-negative and less than the size of the collection parameter name:index
".
Значение в контексте elemnet на конце загружается из api.
Что же мне делать?

Что я уже пробовал:

<pre>using QuickIA.ImportData.PrepareDataSet.Test.Worker;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace QuickIA.ImportData.PrepareDataSet.Test.Model
{
    public class Context
    {
        public Context()
        {
            Elements = new List<ContextElement>();
        }
        internal static IEnumerable<object> ContextElement;
        public List<ContextElement> Elements { get; set; }
        public ContextElement GetElementByDate(string date)
        {  
            foreach (var item in Elements)
            {
                if (item.Data == date)
                    return item;
            } 
            return null;
        } 

        //public void SaveToFile(string fileName) //save to origin file 
        //{
        //    fileName = string.Concat(fileName, ".csv");

        //    if (File.Exists(fileName))
        //    {
        //        File.Delete(fileName);
        //    }
        //    foreach (var e in Elements)
        //    {
        //        File.AppendAllText(fileName, e.Values);
        //        File.AppendAllText(fileName, Environment.NewLine);
        //    }
        //}     
        //public void Save_Reversed(string fileR)
        //{
        //    var sorted = Elements
        //        .SelectMany(a => a.Data)
        //        .OrderBy(a => a)
        //        .Distinct()
        //        .ToList();
              
        //    Elements = Elements.OrderBy(a => a.Data).ToList();
            
        //    fileR = string.Concat(fileR, "_reversed", ".csv");

        //    if (File.Exists(fileR))
        //    {
        //        File.Delete(fileR);   
        //    } 
        //    foreach (var e in Elements)
        //    {
        //        File.AppendAllText(fileR, e.Values);
        //        File.AppendAllText(fileR, Environment.NewLine);
        //    }          
        //}  
        public void Save_Classifier(string fileC)
        {
            //  if (close from previous day > current close price ) = add to file 1 on the end, else add to file 0

            Context y = new Context();
            Context t = new Context();
            decimal today;
            decimal yestarday;

            today = t.Elements[0].Close;
            yestarday = y.Elements[1].Close;

            if (yestarday>today)
            {
                fileC = string.Concat(fileC, "_classifier", ".csv");

                if (File.Exists(fileC))
                {
                    File.Delete(fileC);
                }
                foreach (var e in Elements)
                {
                    File.AppendAllText(fileC, e.Values);
                    File.AppendAllText(fileC,"1" + Environment.NewLine);
                    File.AppendAllText(fileC, Environment.NewLine);
                }
            }
            else
            {
                fileC = string.Concat(fileC, "_classifier", ".csv");

                if (File.Exists(fileC))
                {
                    File.Delete(fileC);
                }
                foreach (var e in Elements)
                {
                    File.AppendAllText(fileC, e.Values);
                    File.AppendAllText(fileC, "0"+ Environment.NewLine);
                    File.AppendAllText(fileC, Environment.NewLine);
                }
            }
        }
    }  
    public class ContextElement
    {
        public ContextElement() { }
        public string Data { get; set; }
        public string Values { get; set; }
        public decimal Open { get; set; }
        public decimal Close { get; set; }
        public decimal High { get; set; }
        public decimal Low { get; set; }
    }
}

F-ES Sitecore

Первое, что вы должны сделать, это научиться задавать хорошо сформулированный вопрос. Если у вас есть ошибка и вы планируете сбросить много кода, по крайней мере, скажите, в какой строке происходит ошибка.

1 Ответов

Рейтинг:
11

Jochen Arndt

Вы создаете новые (пустые) экземпляры Context

Context y = new Context();
Context t = new Context();
а затем получить доступ к первым элементам
today = t.Elements[0].Close;
yestarday = y.Elements[1].Close;
Пустой список имеет нулевой размер так что условие для индекса
Must be non-negative and less than the size of the collection
не встречается.