TomHastjarjanto
TomHastjarjanto

Reputation: 5408

Is there a shorter way to parse attributes as Int (or any other primitive) in LinqToSql

I was basically wondering if it is possible to optimize this code:

AmountComments = Int32.Parse(r.Attribute("AmountComments").Value)

Ideally I would want to write something like

AmountComments = r.Attribute("AmountComments")

r would be a xml tag of type XElement, which is selected before in a Linq query.

Upvotes: 1

Views: 101

Answers (1)

p.campbell
p.campbell

Reputation: 100607

Consider writing an extension method(s) for the type of .Attribute()

One extension method for each type that you'd like out. This way you'd simply be able to:

AmountComments = r.Attribute("AmountComments").ToInt32();


public static class LinqUtils
{
    public static int Int32(this XAttribute attribute)
    {
        return System.Int32.Parse(attribute.Value);
    }
}

Upvotes: 6

Related Questions