SQLlearner
SQLlearner

Reputation: 35

VB.net conversion to c#

I am converting a section of code from VB.net to C# and I am stuck in this section

If Not IsNothing(successNode) Then
    Dim _data As XElement = (From xml In xDoc.Descendants("data") Select xml).FirstOrDefault
    Dim _count As Integer = _data.@count
    If _count > 0 Then
        _objectCollection = New QueryObjectCollection(_data.@listtype)
        For Each item As XElement In _data.Elements(_data.@listtype)
            If Not IsNothing(item.<RECORDNO>) Then
                _objectCollection.Keys.Add(item.<RECORDNO>.Value)
                _objectCollection.Objects.Add(item)
            End If
        Next
    End If
End if

Not sure what is _data.@count and _data.@listtype. Is there are equivalent fuunction ic C#?

Can someone help me convert this section of code to c#?

Upvotes: 1

Views: 131

Answers (2)

Matt Johnson-Pint
Matt Johnson-Pint

Reputation: 241420

It's just VB shorthand.

In VB:

_data.@count
_data.@listtype

In C#:

_data.Attribute("count").Value
_data.Attribute("listtype").Value

Specifically, this is part of a VB.Net language feature of called "XML Literals", and is used in conjunction with LINQ to XML. (C# has LINQ, but does not have XML literals.)

The .@name notation in the VB code, when used on an XElement denotes that you want to retrieve an attribute from that XML element with the specified name. There is also a VB syntax which looks like ...<name> to retrieve an element of the specified name, which would map to the C# .Element("name").Value.

See Overview of LINQ to XML in Visual Basic, and XML Literals Overview.

Upvotes: 10

Sam Nelson
Sam Nelson

Reputation: 387

@ is used to access XAttributes on the XElement represented by _data (whereas the <> notation accesses child XElements). Your C# port should look something like this:

if (successNode != null)
{
    var _data = xDoc.Descendants("data").FirstOrDefault();
    var _count = int.Parse(_data.Attribute("count").Value);
    if(_count > 0)
    {
        var listType = _data.Attribute("listtype").Value;
        _objectCollection = new QueryObjectCollection(listType);
        foreach (var item in _data.Elements(listType))
        {
            var recordNo = item.Element("RECORDNO");
            if (recordNo != null)
            {
                _objectCollection.Keys.Add(recordNo.Value);
                _objectCollection.Objects.Add(item);
            }
        }
    }
}

Upvotes: 6

Related Questions