LinQ to Xml查询并显示空元素

时间:2011-10-17 09:50:19

标签: c# xml linq linq-to-xml

我有以下Xelemnt,其中包含linq查询。查询工作正常,但如果招聘人员名单(List<recruiters>)内没有针对特定人员的招聘人员,我希望能够返回空招聘人员元素。是否有任何简单的方法可以在没有检查xml构建后是否存在特定人员的招聘人员元素的情况下执行此操作,如果没有则添加它?

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"))));

1 个答案:

答案 0 :(得分:1)

您可能希望查看Enumerable类的DefaultIfEmpty方法。 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));