momyuke
momyuke

Reputation: 47

How to add value at list which that list in a list?

i'm setting up a the model that name is "barang". So i create a some list that the type of list is model "barang". And i add list value in that list.

But i have a trouble when i want to add value in one of the list in the list. Can you help me please ?

List<Barang> barangnya = new List<Barang> {
                new Barang {IdBarang = 1, NamaBarang = "Buku Tulis", HargaBarang = 5000},
                new Barang {IdBarang = 2, NamaBarang = "Buku Apa", HargaBarang = 4000},
                new Barang {IdBarang = 3, NamaBarang = "Pulpen", HargaBarang = 2000}
            };

Upvotes: 0

Views: 332

Answers (2)

Prasad Telkikar
Prasad Telkikar

Reputation: 16079

Here you are confused between List<T> and item in the List<T>, Lets clear the confusion first.

List : Represents a strongly typed list of objects

T : The type of elements in the list i.e item in the List

In your case, List<Barang> is a list and Barang is type of element.

List<Barang> barangnya = new List<Barang> ();

Above line creates instance of List<Barang>, now you can add elements to it, here element will be instance of your Barang class.

Here is the code to add new element to your List.

barangnya.Add(new Barang() {IdBarang = 10, NamaBarang = "Prasad", HargaBarang = 6299857});

MSDN : List

Upvotes: 1

Samuel Gregorovič
Samuel Gregorovič

Reputation: 90

Your question is a little unclear, but this is one of the ways to create and add something into the list:

 //creating a list
 List<Barang> barangnya = new List<Barang>();

 //adding items to list
 barangnya.Add(new Barang {IdBarang = 1, NamaBarang = "Buku Tulis", HargaBarang = 5000});

[EDIT] When you insert something into the List, it doesn't become a list. It is just a member of it.

[EDIT n.2] You can refer to the members like this:

//getting the value of the member
var firstBarangInList = barangnya[0];

//changing a member's attribute
barangnya[1].NamaBarang = "New name";

//removing member from list
barangnya.RemoveAt(3);

Upvotes: 1

Related Questions