Linq To Xml Null Checking of attributes

后端 未结 3 2246
小鲜肉
小鲜肉 2021-02-20 18:34

   
   
   

        
3条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-20 19:33

    In C# 6.0 you can use monadic Null-conditional operator ?. After applying it in your example it would look like this:

    var books = from book in booksXml.Descendants("book")
                select new
                {
                    Name = book.Attribute("name")?.Value ?? String.Empty,
                    Price = Convert.ToInt32(book.Attribute("price")?.Value ?? "0"),
                    Special = book.Attribute("special")?.Value ?? String.Empty
                };
    

    You can read more here in part titled Null-conditional operators.

提交回复
热议问题