C# 在LinqToSql中是否有一种较短的方法将属性解析为Int(或任何其他基元)

C# 在LinqToSql中是否有一种较短的方法将属性解析为Int(或任何其他基元),c#,.net,xml,linq,C#,.net,Xml,Linq,我基本上想知道是否有可能优化此代码: AmountComments = Int32.Parse(r.Attribute("AmountComments").Value) 理想情况下,我会想写一些像 AmountComments = r.Attribute("AmountComments") r将是XElement类型的xml标记,它在Linq查询中被选中。考虑为.Attribute类型编写扩展方法 对于您希望输出的每种类型,都有一个扩展方法。这样,您就可以: AmountComments =

我基本上想知道是否有可能优化此代码:

AmountComments = Int32.Parse(r.Attribute("AmountComments").Value)
理想情况下,我会想写一些像

AmountComments = r.Attribute("AmountComments")

r将是XElement类型的xml标记,它在Linq查询中被选中。

考虑为.Attribute类型编写扩展方法

对于您希望输出的每种类型,都有一个扩展方法。这样,您就可以:

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


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

考虑为.Attribute类型编写扩展方法

对于您希望输出的每种类型,都有一个扩展方法。这样,您就可以:

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


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

我猜Value是一个字符串,所以Parse就是这样做的。我猜Value是一个字符串,所以Parse就是这样做的。@Tomh-Cheers,当我看到橙色弹出条说你编辑了答案时,我自己正在填充扩展方法。好编辑@Tomh-Cheers,我自己正在填写扩展方法,这时我看到一个橙色的弹出条,上面说你已经编辑了答案。好编辑!