LINQ select a new class named

I have a linq request where I create several classes that have a Parent property. I am looking for a way to set a parent property as the class I just created. My explanation sucks; here is the code of what i am trying to do.

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

How to 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 that I can do this with a foreach loop, but I would like to know how this is possible with LINQ. Reference: (

EDIT: I tried let x = new state {}, but that didn't help much. I was hoping I could reference x in the constructor like this, but this did not work:

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

There is something similar to this in F # where you can simply say let rec x = ... and then you can access the variable inside the assignment operator. But this is C #, not F #, so.

+6
c # xml linq
source share
2 answers

An interesting problem, and maybe there is a way to do this by setting the properties in the query rule, but I think the other possibility is to move part of this logic to the constructor inside 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 that accepts enumerated City objects. It then iterates over the objects and sets the ParentState property.

Then, instead of setting properties with a query expression, you call the constructor instead.

 // 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 } ); 
+3
source share

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 } } }; 

state variables are the current state. I assume that the "state" var is an XElement and contains data to populate the parentstate property

Hope this helps

0
source share

All Articles