LINQ to XML:如何重新排列查询



我有有效的代码:

.XML:

<parameters>
    <company>asur_nsi</company>
    <password>lapshovva</password>
    <user>dogm_LapshovVA</user>
</parameters>

法典:

XElement documentRoot = XElement.Load(webConfigFilePath);
var param = from p in documentRoot.Descendants("parameters")
            select new
            {
                company = p.Element("company").Value,
                password = p.Element("password").Value,
                user = p.Element("user").Value
            };
foreach (var p in param)
{
    AuthContext ac = new AuthContext()
    {
        Company = p.company,
        Password = p.password,
        User = p.user
    };
}

但是,我想让它更好、更短,并希望立即返回 AuthContext 类型的对象。我想以某种方式将AuthContext对象的创建移动到"选择新"部分。

XElement documentRoot = XElement.Load(webConfigFilePath);
var param = from p in documentRoot.Descendants("parameters")
            select new AuthContext()
            {
                Company = p.Element("company").Value,
                Password = p.Element("password").Value,
                User = p.Element("user").Value
            };
XElement documentRoot = XElement.Load(webConfigFilePath);
var authContexts = (from p in documentRoot.Descendants("parameters")
            select new AuthContext
            {
                Company = p.Element("company").Value,
                Password = p.Element("password").Value,
                User = p.Element("user").Value
            }).ToArray();

只需创建AuthContext而不是匿名类型。

对不起。我刚刚弄清楚如何做我想做的事:

var config = XElement.Load(webConfigFilePath).Descendants("parameters").Single();
AuthContext ac = new AuthContext
{
    Company = config.Element("company").Value,
    Password = config.Element("password").Value,
    User = config.Element("user").Value
};

无论如何,谢谢你。

最新更新