LINQ选择具有名称的新类

for*_*ora 6 c# xml linq

我有一个linq查询,我在其中创建了几个具有Parent属性的类.我正在寻找一种方法将父属性设置为我刚刚创建的类.我的解释很糟糕; 这是我正在尝试做的代码.

var query = from states in xml.Elements()
                    select new State
                    {
                        Children = from cities in states.Elements()
                                   select new City()
                                    {
                                        ParentState = **???**;
                                    }
                    };
Run Code Online (Sandbox Code Playgroud)

如何设置ParentState属性?如果我能做点什么的话

select new State as newState
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

那会很酷,但我不能.我知道我可以用foreach循环来做到这一点,但是我想学习如何使用LINQ来做这件事.救命 :(

编辑:我试过让x =新的州{},但这没有多大帮助.我希望我可以像这样在构造函数中引用x,但它没有成功:

let x = new State 
{  
    Children = from cities in states.Elements()
               select new City{ ParentState = x }
}
select x;
Run Code Online (Sandbox Code Playgroud)

在F#中,有一些类似的东西,你可以简单地说让rec x = ...然后你可以引用赋值语句中的变量.但这是C#而不是F#所以无论如何.

sTo*_*rov 0

嘿,我想这就是你需要的

    var query = from states in xml.Elements()
                        select new State
                        {
                            Children = from cities in states.Elements()
                                       select new City()
                                        {
                                            ParentState = new State{
                                                Property1 = states.XElement("Property1").Value
}
                                        }
                        };
Run Code Online (Sandbox Code Playgroud)

变量 states 是当前状态。我假设“states”var 是一个 XElement,并保存数据以填充parentstate 属性

希望这可以帮助