c# – 如何告诉LINQ忽略不存在的属性?
发布时间:2020-12-16 01:30:55 所属栏目:百科 来源:网络整理
导读:只要 XML的每个元素都具有“Id”属性,以下代码就可以工作. 但是,如果元素没有id属性,LINQ会抛出NullReferenceException. 如何指定如果没有Id属性,只需指定null或空白? using System;using System.Linq;using System.Xml.Linq;namespace TestXmlElement2834{
只要
XML的每个元素都具有“Id”属性,以下代码就可以工作.
但是,如果元素没有id属性,LINQ会抛出NullReferenceException. 如何指定如果没有Id属性,只需指定null或空白? using System; using System.Linq; using System.Xml.Linq; namespace TestXmlElement2834 { class Program { static void Main(string[] args) { XElement content = new XElement("content",new XElement("item",new XAttribute("id","4")),new XAttribute("idCode","firstForm")) ); var contentItems = from contentItem in content.Descendants("item") select new ContentItem { Id = contentItem.Attribute("id").Value }; foreach (var contentItem in contentItems) { Console.WriteLine(contentItem.Id); } Console.ReadLine(); } } class ContentItem { public string Id { get; set; } public string IdCode { get; set; } } } 解决方法
(第2次编辑)
哦 – 发现了一种更简单的方法;-p from contentItem in content.Descendants("item") select new ContentItem { Id = (string)contentItem.Attribute("id") }; 这要归功于XAttribute等上灵活的静态转换运算符. (原版的) from contentItem in content.Descendants("item") let idAttrib = contentItem.Attribute("id") select new ContentItem { Id = idAttrib == null ? "" : idAttrib.Value }; (第1次编辑) 或者添加扩展方法: static string AttributeValue(this XElement element,XName name) { var attrib = element.Attribute(name); return attrib == null ? null : attrib.Value; } 并使用: from contentItem in content.Descendants("item") select new ContentItem { Id = contentItem.AttributeValue("id") }; (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |