0

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()))
};
  1. Get dbY items that are associated with the dbX item (FK)
  2. Deserialize all dbY items to object Y
  3. 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.

Community
  • 1
  • 1
R3dn0l
  • 81
  • 1
  • 1
  • 11
  • This is what a constructor should be used for. If you have `var x = new X();` then your constructor `public X(){...}` should do all the initialization work. Same goes then for the classes `Y` and `Z` – Markus Deibel Nov 06 '19 at 14:43
  • @MarkusDeibel I don't think this is possible because I'm using json. The challenge here is that the json is not in the same table. datastoreY and datastoreZ have their own json column. They are linked with a foreign key. – R3dn0l Nov 06 '19 at 15:10

0 Answers0