I've searched through quite a bit of questions on here and can't find an answer in this situation. I must be doing something completely wrong, because this seems like something that should be fairly simple. If there is another question I'm not finding if someone could point me in the right direction I'd really appreciate it.
I have an Insert method that inserts category guid's into a blog post. I am trying to insert the entire blog post all at once. The code in question is:
new XElement("categories", blog.categories.Select(x => new XElement("category", x))),
and it works, as long as blog.categories is not null, but when it's null it errors. Blog categories is a guid array. If it were a string I would put a ??, but this doesn't work for anything else but a string.
Everything fits so nicely, it would seem wrong to add the blog, then find it again, check for a null and if not add the elements separately. Any insights would be appreciated.
What do you mean ??
doesn't work for non-strings? Yes it does.
(blog.categories ?? new Guid[0]).Select(x => new XElement("category", x))
It's not the nicest, but it's probably nicer than any alternatives, since as you said creating an instance of the blog then adding this post-facto could be a hassle.
You could also, of course, create your categories XElement before the blog:
XElement categories;
if(blog.categories == null)
{
categories = new XElement("categories");
}
else
{
categories = new XElement("categories", blog.categories.Select(x => new XElement("category", x)));
}
Then just reference categories
later on in place of what you do now.