【问题标题】:linq to xml (c# to vb.net conversion)linq to xml (c# to vb.net 转换)
【发布时间】:2010-10-22 13:23:37
【问题描述】:

下面的 VB.net 语法是干什么用的?

   var list = xd.Descendants("product")
   .Select(element =>new 
   { 
      Title = element.Attribute("title").Value,                   
      Duration = element.Element("duration").Value 
   }).ToList(); 

【问题讨论】:

  • 得到了一些东西:Dim list1 = (From x In xd.Descendants("product") _ .Select(Function(element) _ New With {.Title = element.Attribute("title") .Value})).ToList() 需要包含 'duration' .. 如何??

标签: c# vb.net .net-3.5 linq-to-xml lambda


【解决方案1】:

试试这个:

Dim list = 
   From element In xd.Descendants("product")
   Select New With { _ 
       .Title = element.Attribute("title").Value, _
       .Duration = element.Element("duration").Value }

您不需要使用 Linq 语法,只需使用底层扩展即可:

Dim list = xd.Descendants("product"). _
    Select(Function(element) _ 
        New With { _ 
           .Title = element.Attribute("title").Value, _
           .Duration = element.Element("duration").Value _
        }). _
    ToList()

【讨论】:

  • 感谢 Keiths - 它帮我解决了问题
【解决方案2】:

如果您使用的是 VB,这里有一些语法糖:

Dim list = 
   From element In xd...<product>
   Select New With { _ 
       .Title = element.@title, _
       .Duration = element.<duration>.Value }

好的部分是,如果您的文档有一个 xsd(并且您可以通过 Visual Studio 从一个或多个 xml 文档推断它来创建一个),您几乎可以像导入命名空间和 Visual Studio 一样导入它编写查询时将为您提供智能感知完成。

一些参考资料:

【讨论】:

  • CStr 函数有什么用? element.@title 不返回字符串吗?
  • 这绝对是真的,我现在不明白为什么我把它放在那里。
猜你喜欢
  • 1970-01-01
  • 2010-11-05
  • 1970-01-01
  • 2010-11-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-17
相关资源
最近更新 更多