ElektroStudios
ElektroStudios

Reputation: 20464

Translate simple code with C#6 syntax to Vb.Net

Someone could help me to translate this simple snippet that uses the new C# 6 syntax, to Vb.Net?

The resulting LINQ query is incomplete (wrong syntax) when doing a translation in some online services like one from Telerik.

/// <summary>
///     An XElement extension method that removes all namespaces described by @this.
/// </summary>
/// <param name="this">The @this to act on.</param>
/// <returns>An XElement.</returns>
public static XElement RemoveAllNamespaces(this XElement @this)
{
    return new XElement(@this.Name.LocalName,
        (from n in @this.Nodes()
            select ((n is XElement) ? RemoveAllNamespaces(n as XElement) : n)),
        (@this.HasAttributes) ? (from a in @this.Attributes() select a) : null);
}

Upvotes: 0

Views: 106

Answers (2)

Dave Doknjas
Dave Doknjas

Reputation: 6542

Including the xml comments, and correcting the 'RemoveAllNamespaces' error in the other answer, your VB equivalent is:

''' <summary>
'''     An XElement extension method that removes all namespaces described by @this.
''' </summary>
''' <param name="this">The @this to act on.</param>
''' <returns>An XElement.</returns>
<System.Runtime.CompilerServices.Extension> _
Public Function RemoveAllNamespaces(ByVal this As XElement) As XElement
    Return New XElement(this.Name.LocalName, (
        From n In this.Nodes()
        Select (If(TypeOf n Is XElement, RemoveAllNamespaces(TryCast(n, XElement)), n))),If(this.HasAttributes, (
            From a In this.Attributes()
            Select a), Nothing))
End Function

Upvotes: 2

A.Konzel
A.Konzel

Reputation: 1980

Give this a shot:

<System.Runtime.CompilerServices.Extension()> _
Public Function RemoveAllNamespaces(this As XElement) As XElement
    Return New XElement(this.Name.LocalName,
        (From n In this.Nodes
         Select (If(TypeOf n Is XElement, TryCast(n, XElement).RemoveAllNamespaces(), n))),
        If((this.HasAttributes), (From a In this.Attributes Select a), Nothing))
End Function

In case you'll be converting other code, here's the steps I took:

  • Added the Extension attribute, because VB does not have syntax like C# does for creating extension methods.
  • Replaced the C# ternary operator with VB If(condition, true, false).
  • Replaced C# casts with VB TryCast(object, type).
  • Replaced C# type checking with VB TypeOf object Is type.
  • Replaced C# null with VB Nothing.

Upvotes: 1

Related Questions