I have some models setup as follows:
public class Form
{
public int FormId { get; set; }
public virtual ICollection<SubForm> SubForms{ get; set; }
}
public class SubForm
{
public int SubFormId { get; set; }
public virtual Form Form {get; set;}
}
I have a list like this:
List<SubForm> subForms; <-- already populated, each subform has a form parent.
How do I get it in a format like this optimally (lambda preferred)
List<Form> formsWithChildren;
You can group by the
FormIdthen assign the grouped subforms to each newFormitem as follows:EDIT: if other properties exist then you would have to map them in the object initializer, but this could become tedious, and isn’t the best option if you intend to reuse this type of query in other scenarios. I suggest creating a new
Formobject and mapping it using AutoMapper.If you decide to use AutoMapper the approach would be similar to this:
To learn more refer to the AutoMapper site.
Alternately, you could take an approach as follows, although this modifies the existing items so be aware of that.
In both approaches shown above you will need to implement
Equalson theFormclass in order to GroupBy theForminstead ofFormId:You could extend the equality and
GetHashCodemethods to use the properties to determine uniqueness. Currently it only relies on theFormId.