I'm new to C# and what I want to do here is add a conditional to return an empty array if the loop that I have set for my DataPoints API response variable is out of range.
Right now it throws an exception but what I want it to do is instead of throwing the exception just return an empty array in the DataPoints API response. How would I do that?
exception
"Index was out of range. Must be non-negative and less than the size of the collection.\r\nParameter name: index""
code sample
public void BuildDataPoints()
{
// Create WspViewList from ViewData
WspViewList dataPointBuilder = new WspViewList(ViewData);
List<DataPointAPI> dataset = new List<DataPointAPI>();
WspViewCol _labelCol = null;
List<WspViewCol> yAxisCols = new List<WspViewCol>();
//Iterate through the view's columns to find special chart columns
foreach (WspViewCol col in dataPointBuilder._cols)
{
if (col._baseCol.DbrViewCol.YAxis)
yAxisCols.Add(col);
if (col._baseCol.DbrViewCol.XAxis)
_labelCol = col;
}
var DataPoints = new DataPoints();
// Generate DataPoints (or something similar) from the newly constructed WspViewList.
foreach (WspViewRow row in dataPointBuilder)
{
var dataPointList = row.OriginalData.TrimStart('[').TrimEnd(']').Split(',').ToList();
for (var index = 2; index < dataPointList.Count; index++)
{
var dataPoint = dataPointList[index];
if (string.IsNullOrEmpty(dataPoint))
continue;
ChartDataObject cdo;
if (DataPoints.datasets.Count <= index - 2)
{
cdo = new ChartDataObject();
DataPoints.datasets.Add(cdo);
cdo.label = ColumnObjects[index].propertyName;
}
else
cdo = DataPoints.datasets[index - 2];
cdo.data.Add(dataPoint);
<—-THIS LINE THROWS THE ERROR —>
DataPoints.datasets[index - 2] = cdo;
}
DataPointAPI DataPointResponse = new DataPointAPI()
{
data = DataPoints,
};
dataset.Add(DataPointResponse);
}
// Set some class field to contain these datapoints
ChartData = dataset;
}
public class DataPointAPI
{
public DataPoints data;
}
public class DataPoints
{
public List<string> labels { get; set; }
public List<ChartDataObject> datasets { get; set; }
public DataPoints()
{
labels = new List<string>();
datasets = new List<ChartDataObject>();
}
}
public class ChartDataObject
{
public string label { get; set; }
public List<string> data { get; set; }
public ChartDataObject()
{
data = new List<string>();
}
}