I’m looping through an array of items nested within another array of items.
Almost always, the inner array contains 5 indexes, but there is an off chance that the feed I’m consuming will only have 4 indexes in it.
When I add the indexes to my ViewModel, if the fifth index is missing, everything blows up.
How can I prevent “Index is outside the bounds of the array” errors in this specific scenario?
private List<ImageViewModel> ConvertSmugMugModel(SmugMugGallery smugMugGallery)
{
return smugMugGallery.Channel.Items.Select(i => new ImageViewModel
{
TinyImage = i.Group.Contents[0].Url,
ThumbnailUrl = i.Group.Contents[1].Url,
SmallImageUrl = i.Group.Contents[2].Url,
MediumImageUrl = i.Group.Contents[3].Url,
LargeImageUrl = i.Group.Contents[4].Url
}).ToList();
}
*note: I’m not opposed to moving to an iCollection or some other object if using an array is not the best fit. I just didn’t want to add bloat if I didn’t need to.
Edit
Kal asked what the the model looks like in a comment below.
[XmlRoot("rss")]
public class SmugMugGallery
{
[XmlElement("channel")]
public m_Channel Channel { get; set; }
public class m_Channel
{
[XmlElement("item")]
public Item[] Items { get; set; }
public class Item
{
[XmlElement("group", Namespace = "http://search.yahoo.com/mrss/")]
public m_Group Group { get; set; }
public class m_Group
{
[XmlElement("content", Namespace = "http://search.yahoo.com/mrss/")]
public Content[] Contents { get; set; }
public class Content
{
[XmlAttribute("url")]
public string Url { get; set; }
}
}
}
}
}
My first thought is just use the ? operator, like so:
You may also want to put that check into the rest of them also, unless you’re 101% sure you won’t run into less than 4 elements. Thusly: