I have a linq query where I am creating several classes which have a Parent property on them. I am looking for a way to set the parent property to be the class I just created. My explanation sucks; here's code of what I'm trying to do.
var query = from states in xml.Elements()
select new State
{
Children = from cities in states.Elements()
select new City()
{
ParentState = **???**;
}
开发者_开发技巧 };
How do I set the ParentState property? If I could do something like
select new State as newState
{
...
}
that would be cool, but I can't. I know I can do this with a foreach loop, but I would like to learn how, if possible, to do this with LINQ. Help :(
EDIT: I tried let x = new State{ } but that didn't help much. I was hoping I could refer to x in the constructor like this but it didn't work out:
let x = new State
{
Children = from cities in states.Elements()
select new City{ ParentState = x }
}
select x;
In F#, there is something similar to this where you can simply say let rec x = ... and then you can refer to the variable inside of the assignment statement. But this is C# not F# so whatever.
Interesting problem, and there may certainly be a way to do it by setting the properties right in the query statement, but I think another possibility is to move some of that logic to a constructor within State. Consider the following code example
class State
{
public int Id { get; set; }
public List<City> Children { get; set; }
public State(int id, IEnumerable<City> childrenCities)
{
this.Id = id;
this.Children = childrenCities.ToList();
foreach (City city in this.Children)
city.ParentState = this;
}
}
This State class has a constructor which accepts an enumerable of City objects. It then loops over the objects and sets the ParentState property.
And then instead of setting the properties with the query expression, you instead invoke the constructor.
// not LINQ-to-XML, just an example
var states = from i in Enumerable.Range(0, 10)
select new State(
i,
from j in Enumerable.Range(0, 5)
select new City
{
Id = j
}
);
Hey, I think this is what you need
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
}
}
};
the variable states is the current state. I presume the "states" var is an XElement and holds the data to populate the parentstate property
Hope this helps
精彩评论