I'd like to know if the following is possible and if it would have any performance benefits.
Given this structure;
public class X
{
[JsonIgnore]
public List<Y> Y { get; set; }
}
public class Y
{
[JsonIgnore]
public List<Z> Z { get; set; }
}
public class Z
{
...
}
short version
Can I initialize X.Y.Z in one line?
Working (foreach) version;
X x = null;
var dbitem = db.SingleOrDefault(...);
if (dbitem != null)
{
x = new X
{
Y = dbX.dbY.Select(a =>
JsonConvert.DeserializeObject<Y>(a.json)).ToList()
};
x.Y.ForEach(a =>
a.Z = dbX.dbY.Single(b => b.id == a.id)
.dbZ.Select(q => JsonConvert.DeserializeObject<Z>(q.json)).ToList());
}
Experimental
Create Y and Z in one go, no need to query .Single(b => b.id == a.id)
x = new X
{
Y = dbX.dbY.Select(a =>
JsonConvert.DeserializeObject<Y>(a.json).Z.AddRange(
a.dbZ.Select(b =>
JsonConvert.DeserializeObject<Z>(b.json)).ToList()))
};
- Get dbY items that are associated with the dbX item (FK)
- Deserialize all dbY items to object Y
- Object Y has List property which I want to initalize at the level of Y. I want to do this because at that point I have a reference to all Z objects (by FK).
Step 3 is where I don't know what to do. How to intialize those Z objects from that reference?
If the question is unclear or title doesn't reflect question please let me know.