Reference Object in Initializer Child Property

M

Matt Sollars

Hi!

Does anyone know how to reference the object created via an object
initializer when setting a child property? It's hard to write into a
sentence. Suppose the following summary class for a categories in a DB.

public class CategorySummary {
public string Name { get; set; }
public CategorySummary ParentCategory { get; set; }
public List<CategorySummary> ChildCategories { get; set; }
}


If I get the parent (top-level) categories via a LINQ query, set the
child categories via an embedded query, and want to set the children's
ParentCategory to the previously initialized object, how would I? Here's
the LINQ query without the ParentCategory set.

var Categories = from C in DataContext.Categories
where !C.ParentCategoryId.HasValue
select new CategorySummary() {
Name = C.Name,
ChildCategories = (
from CC in DataContext.Categories
where CC.ParentCategoryId == C.CategoryId
select new CategorySummary() {
Name = CC.Name,
ParentCategory = ??
}
).ToList()
};


I want to set the embedded object's ParentCategory to the outer object
initializer result (the first CategorySummary initializer. If only I
could alias the object being initialized.


Thanks in advance for any help!

-Matt
 
J

Jon Skeet [C# MVP]

Matt Sollars said:
Does anyone know how to reference the object created via an object
initializer when setting a child property?

You can't. It only becomes available afterwards.

It's a fairly rare requirement, and would have been a complex thing to
include. But I agree that where you *do* need it, it's a pain that it's
not there...
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top