简体   繁体   English

如何在列表中的列表中增加值?

[英]How to add value at list which that list in a list?

i'm setting up a the model that name is "barang". 我正在建立一个名为“ barang”的模型。 So i create a some list that the type of list is model "barang". 所以我创建了一个列表,列表的类型是模型“ 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}
            };

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: [编辑n.2]您可以这样引用成员:

//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);

Here you are confused between List<T> and item in the List<T> , Lets clear the confusion first. 在这里,您在List<T>List<T> item in the List<T>之间感到困惑,让我们先清除混乱。

List : Represents a strongly typed list of objects 列表:表示对象的强类型列表

T : The type of elements in the list ie item in the List T:列表中元素的类型,即列表中的项目

In your case, List<Barang> is a list and Barang is type of element. 在您的情况下, List<Barang>是列表,而Barang是元素的类型。

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. 上面的行创建了List<Barang>实例,现在您可以向其中添加元素,这里element将是您的Barang类的实例。

Here is the code to add new element to your List. 这是将新元素添加到列表中的代码。

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

MSDN : List MSDN:列表

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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