fedor333
fedor333

Reputation: 45

LinQ to Xml query and displaying empty elements

I have the following Xelemnt that contains a linq query within it. The query works fine but I want to be able to return an empty recruiter element if there are no recruiters within the recruiter list (List<recruiters>) for a particular person. Is there any easy way to do this without checking to see if a recruiter element exists for a specific person after the xml has been built and if not then adding it?

XElement Person =
                    new XElement("Person",
                    new XElement("title", ""),
                    new XElement("id",""),
                    new XElement("url", ""),
                     (from Recruiter r in recruiters
                        where r.id == p.id
                        select new XElement("Recruiter",
                        new XElement("recruitername", r.recruitername),
                        new XElement("recruiteremail", r.recruiteremail),
                        new XElement("recruiterphone"))));

Upvotes: 0

Views: 563

Answers (1)

jpk
jpk

Reputation: 81

You might want to have a look at the DefaultIfEmpty method of Enumerable class. msdn

XElement defaultRecruiter = new XElement("Recruiter");
XElement Person =
                new XElement("Person",
                new XElement("title", ""),
                new XElement("id",""),
                new XElement("url", ""),
                 (from Recruiter r in recruiters
                    where r.id == p.id
                    select new XElement("Recruiter",
                    new XElement("recruitername", r.recruitername),
                    new XElement("recruiteremail", r.recruiteremail),
                    new XElement("recruiterphone"))).DefaultIfEmpty(defaultRecruiter));

Upvotes: 1

Related Questions