BumbleBee
BumbleBee

Reputation: 10789

Check for Null while Creating XML document from object list

I want to create an XML document from object list. How to handle Null in the transform.

  XElement xml = new XElement("people",
                            from p in PPL
                            select new XElement("person",
                                        new XElement("id", p.ID),
                                        new XElement("firstname", p.FirstName),
                                        new XElement("lastname", p.LastName),
                                        new XElement("idrole", p.IDRole)));

As shown in the above example if the PPL is null then my xml should have just <\people> Now I am getting NUllreferenc error.

Thanks in advance BB

Upvotes: 0

Views: 524

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500875

One option is to use the null coalescing operator:

from p in PPL ?? Enumerable.Empty<Person>()

If you need to do this for a collection of an anonymous type, you could create an extension method:

public static IEnumerable<TSource> EmptyIfNull<TSource>
    (this IEnumerable<TSource> source)
{
    return source ?? Enumerable.Empty<TSource>();
}

then your query could use

from p in PPL.EmptyIfNull()

Upvotes: 4

Related Questions