简体   繁体   中英

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.

I see two choices: set oray3 to a new Liste object and set its properties rather than reuing the reference, or copy oray3 to a new Liste object and add that to the list.

It's not clear why you're reusing oray3 in the first place to kniw which of those is better.

Just make Liste a struct instead of a class ie

public struct Lex
{
    public Lex() 
    { 

    }

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

Classes in C# a reference type and so are passed by reference whereas structs are value types and so are passed by value.

Reference types pass around a reference to the declared variable so when they are assigned to another variable and changed, both variables are updated.

Value types simply copy their values when assigned so changes only occur on the variable that the changes were made to.

More info on value type and reference types here: https://www.tutorialsteacher.com/csharp/csharp-value-type-and-reference-type

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>();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM