I have a page that can pass anywhere from 1 array to 3 arrays.
My current code works but only if each array is populated with items.
[HttpPost, ValidateInput(false)]
public ActionResult AddCampaign(string campaignName, string editor1, Int32[]
productImages, Int32[] lifestyleImages, Int32[] logoImages)
{
// Add image list to CampaignImages table
// Combine image array list into a single array
var imageList = productImages.Concat(lifestyleImages).Concat(logoImages).ToArray();
return RedirectToAction("AddCampaign", "Admin");
}
Each array is the exact same it will only hold an ID of an image. This will work as long as all 3 arrays have something in them. But if one is null it errors out.
What I need is a single array that is a combination of all 3 arrays, productImages
, lifestyleImages
, logoImages
.
Not sure what I am missing.
Well you're missing the fact that Concat
will throw an exception if you pass it a null reference... but it's easy enough to fix. Either write an extension method like this:
public static IEnumerable<T> NullToEmpty<T>(this IEnumerable<T> src)
{
return src ?? Enumerable.Empty<T>();
}
And call it as:
var imageList = productImages.NullToEmpty()
.Concat(lifestyleImages.NullToEmpty())
.Concat(logoImages.NullToEmpty())
.ToArray();
... or just use the null-coalescing operator directly:
var empty = Enumerable.Empty<int>();
var imageList = (productImages ?? empty).Concat(lifeStyleImages ?? empty)
.Concat(logoImages ?? empty)
.ToArray();
See more on this question at Stackoverflow