Home > front end >  How to add items to existing list of objects?
How to add items to existing list of objects?

Time:02-05

I have three classes:

public class M2ArticleMain
{
   public int Id { get; set; }
   public List<M2ArticleAttributeWeb> Attribut_Web { get; set; }
}

public class M2ArticleAttributeWeb
{
   public int Web_Id { get; set; }
   public M2ArticleTmpMainSkus Variants { get; set; }
}

public class M2ArticleTmpMainSkus
{
   public DateTime TimeAdded { get; set; }
   public List<string> Skus { get; set; }
}

And I have two Lists in my code like this:

List<M2ArticleMain> data = new List<M2ArticleMain>();
List<M2ArticleAttributeWeb> attb = new List<M2ArticleAttributeWeb>();

In some part of my code firstly I (from foreach loop) add data to attb list where I add only only some data (because I don't have all data at this point), like this:

...
attb.Add(new M2ArticleAttributeWeb
    {
       Web_id = item.Id, //(item is from foreach loop)
       Variants = null   //this is **importat**, I left null for later to add it
    });

Next, after I fill attb, I add all this to data list:

...
data.Add(new M2ArticleMain
   {
      Id = item.Id_Pk,  //this is also from foreach loop,
      Attribut_Web = attb  //now in this part I have only data for Web_id and not Variants
   }

Now my question is How to Add items later to data list to object Variants?

Something like this:

data.AddRange( "how to point to Variants" = some data);

CodePudding user response:

The M2ArticleAttributeWeb type holding your Variants property is the member of a collection. That is, there are potentially many of them. You can reference an individual Variants property like this:

data[0].Attribut_Web[0].Variants

But you need to know which items you want to add map to which data and Attribut_Web indexes/objects in order to assign them properly. That probably means another loop, or even a nested loop. That is, you can see all of your Variants properties in a loop like this:

foreach(var main in data)
{
    foreach(var attrw in main)
    {
        var v = attrw.Variants;
        // do something with v
        Console.WriteLine(v);
        // **OR**
        attrw.Variants = // assign some object
    }
}

It's also much better practice to create your collection properties with the object, and then give them private set attributes:

public class M2ArticleMain
{
   public int Id { get; set; }
   public List<M2ArticleAttributeWeb> Attribut_Web { get; private set; } = new List<M2ArticleAttributeWeb>();
}

public class M2ArticleAttributeWeb
{
   public int Web_Id { get; set; }
   public M2ArticleTmpMainSkus Variants { get; set; } 
}

public class M2ArticleTmpMainSkus
{
   public DateTime TimeAdded { get; set; }
   public List<string> Skus { get; private set; } = new List<string>();
}

Now instead of assigning Attribut_Web = attb, you would need to .Add() to the existing List.

  •  Tags:  
  • Related