Reputation:
var entries = from video in Video.GetTopVideos().AsEnumerable()
select
new XElement("item",
new XElement("title", video.Title),
new XElement("category", video.Tags[video.Tags.Count-1].Name),
//...........
If the property video.Tags==null then an exception throws. Can I check for null value?
Upvotes: 0
Views: 629
Reputation: 134125
Yes, you can:
var entries = from video in Video.GetTopVideos().AsEnumerable()
where video.Tags != null
select
new XElement("item",
new XElement("title", video.Title),
new XElement("category", video.Tags[video.Tags.Count-1].Name),
//...........
Or, if you want to make sure that you always have something even if the Tags
property is null
:
var entries = from video in Video.GetTopVideos().AsEnumerable()
let cat = (video.Tags != null && video.Tags.Count > 0) ? video.Tags[video.Tags.Count-1].Name : "**No Category**
select
new XElement("item",
new XElement("title", video.Title),
new XElement("category", cat),
//...........
Upvotes: 2
Reputation: 126972
Yes, you can. You can rewrite that line as
video.Tags != null ? new XElement(...) : null
If Tags
is null, no XElement
will be emitted for category
in your resulting XML. You could, of course, elect to provide another default element instead of null, if you wish.
Upvotes: 2
Reputation: 1809
Add a where clause that states:
where video.Tags != null
This will limit your results to only those that do have Tags.
Your query will ultimately look like the following:
var entries = from video in Video.GetTopVideos().AsEnumerable()
where video.Tags != null
select new XElement("item",
new XElement("title", video.Title),
new XElement("category", video.Tags[video.Tags.Count-1].Name),
//...........
Upvotes: 0