How to Insert only values of a class into another list class C#?

image that you defined a class as below;

public class Liste
{
    public int valueInt { get; set; }
    public List<string> valueString = new List<string>();
}

and I defined a varible which is also a list;

  public List <Liste> oray2 = new List <Liste>();
  public Liste oray3 = new Liste();

I would like to add value to a oray2 List manually,

        oray3.valueInt = 10;
        oray3.valueString.Add("Text1");
        oray3.valueString.Add("Text2");
        oray3.valueString.Add("Text3");

        oray2.Add(oray3);

        oray3.valueString.Remove("Text2");

This also effects oray2 List. So it seems

oray2.Add(oray3);

is not adding values to oray2 class but oray2[0] seems linked to oray3 class.

So What is the best and efficient way to add values of oray3 to oray2 without a link between oray3 and oray2[0] so resulting changing in oray3 will not affect oray2 list values?

My best solution;

oray3=null;

or

oray3=new Liste();

worked like a charm.

>Solution :

I think this is what you want to do. This way a new oray3 object is created each time you call the GetOray3().

List<Liste> oray2 = new List<Liste>();

oray2.Add(GetOray3());
oray2.Add(GetOray3());
oray2.Add(GetOray3());

static Liste GetOray3()
{
    Liste oray3 = new Liste();

    oray3.valueInt = 10;
    oray3.valueString.Add("Text1");
    oray3.valueString.Add("Text2");
    oray3.valueString.Add("Text3");

    return oray3;
}

public class Liste
{
    public int valueInt { get; set; }
    public List<string> valueString = new List<string>();
}

Leave a Reply