LINQ to XML - 选择强类型对象(VB)

时间:2013-09-12 14:56:55

标签: vb.net linq-to-xml

这不是一个大问题,但它让我烦恼。我知道如何选择一个强类型的集合(List(Of T)),但我找不到一个整理方法来为一个不是List的对象。

这有效:

Dim x = From a In response...<artist> _
Select New MBArtistInfo With {.MBID = a.@id, .Name = a.<name>.Value, .Gender = a.<gender>.Value}
Return x(0)

但必须这样做很烦人。

我在其他地方看到过C#解决方案:

var x = from a In response...<artist>
select new MBArtistInfo
{
MBID = etc

但我无法将其转换为VB。

有没有人这样做过?

1 个答案:

答案 0 :(得分:0)

只需跳过课程名称:

Dim x = From a In response...<artist> _
        Select New With { .MBID = a.@id, .Name = a.<name>.Value, .Gender = a.<gender>.Value }

但它会给你IEnumerable(Of T),其中Tanonymous type。你不应该从你的方法中返回这样的对象:

  

例如,匿名类型不能用于定义方法   签名,声明另一个变量或字段,或任何类型   宣言。 因此,匿名类型不适合您   必须跨方法分享信息。

修改

要从集合中仅使用First / FirstOrDefault方法获取一个元素:

Dim x = (From a In response...<artist> _
        Select New With { .MBID = a.@id, .Name = a.<name>.Value }).FirstOrDefault();