'Add items to List<object>
I am new to OOPS. I want to add items to a list of objects
Class ABC
{ int a; int b; int c;}
List<ABC> listabc = new List<ABC>();
I am not able to add all three properties of object together as they are being fetched at different times, but I want them to be a part of the same object, for example: I have different calls to add it to the list
listabc.Add(new ABC {a = 10});
listabc.Add(new ABC {b = 20});
listabc.Add(new ABC {c = 30});
listabc.Add(new ABC {a = 40});
listabc.Add(new ABC {b = 50});
listabc.Add(new ABC {c = 60});
I want this to be ({10,20,30},{40,50,60}) instead this will add ({10,0,0},{0,20,0},{0,0,30},{40,0,0},{0,50,0},{0,0,60}) how should I add it to the list?
Solution 1:[1]
You need to add them all at once.
listabc.Add(new ABC {a = 10, b=20, c=30});
In your example, you are creating a new class each time and populating a different property. You are getting zeros when you do not provide value because the default value for int is 0;
Solution 2:[2]
One thing you could do is set up a constructor on your class to pass through the variables:
public class ABC
{
public int A { get; set; }
public int B { get; set; }
public int C { get; set; }
public ABC (int a, int b, int c) {
A = a;
B = b;
C = c;
}
}
Then when you populate your class, you can specify the values in your constructor:
List<ABC> listabc = new List<ABC>();
listabc.Add(new ABC(10,20,30));
Otherwise, when you add an object you need to ensure you specify all parameters.
The way you were adding them, it was the equivalent of only passing through one value, e.g.
listabc.Add(new ABC(10,0,0));
listabc.Add(new ABC(0,20,0));
listabc.Add(new ABC(0,0,30));
Solution 3:[3]
Only
listabc.Add(new ABC {10, 20, 30});
Console.Write ($"{listabc[0].a}, {listabc[0].b}, {listabc[0].c}");
it's all
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Andre.Santarosa |
| Solution 2 | Mike |
| Solution 3 | José Donoso |
