简体   繁体   English

将项目添加到列表<> c#

[英]Adding item to List<> c#

i have an 2D array which i am trying to write into a List so i can bind it with a datagrid. 我有一个2D数组,我试图写入一个List,所以我可以绑定它与数据网格。 below is my code. 下面是我的代码。

        string[,] array = new string[8,4];
        array[counting2, 0] = txtSend.Text;
        array[counting2, 1] = One;
        array[counting2, 2] = Two;
        array[counting2, 3] = Three;


        List<Testing> Hello1 = new List<Testing>();

        Testing Hello = new Testing();
        for (int i = 0; i <= counting2;i++ )
        {
            Hello.year = array[counting2, 0];
            Hello.One = array[counting2, 1];
            Hello.Two = array[counting2, 2];
            Hello.Three = array[counting2, 3];
            Hello1.Add(Hello);

        }

       dataGrid1.ItemsSource = Hello1;

What is see is when my array contain 3 rows the data grids shows 3 rows with the same data instead of 3 diffrent data. 可以看到的是,当我的数组包含3行时,数据网格显示3行,具有相同的数据,而不是3个不同的数据。 I am guessing is that i am adding Hello to the list 3 times. 我猜是我将Hello添加到列表中3次。

But do i change the Hello to a variabele so each time the for loop loops its another name. 但是我是否将Hello更改为varbele,因此每次for循环都会循环另一个名称。

Ne Ideas ?? Ne Ideas ??

Move the declaration of 移动声明

Testing Hello = new Testing();

Inside the loop 在循环内

So you have; 所以你有了;

    for (int i = 0; i <= counting2;i++ )
    {
        Testing Hello = new Testing();
        Hello.year = array[counting2, 0];
        Hello.One = array[counting2, 1];
        Hello.Two = array[counting2, 2];
        Hello.Three = array[counting2, 3];
        Hello1.Add(Hello);

    }

The problem is exactly as you said: you're adding the same element to the list three times. 问题正如您所说的那样:您将相同的元素添加到列表中三次。 And you're changing it with each iteration, but it's always the same object. 而且你每次迭代都会改变它,但它总是相同的对象。 You should move the creation of the object into the cycle, in order to create a different object each time. 您应该将对象的创建移动到循环中,以便每次都创建不同的对象。

    for (int i = 0; i <= counting2;i++ )
    {
        Testing Hello = new Testing();
        Hello.year = array[counting2, 0];
        Hello.One = array[counting2, 1];
        Hello.Two = array[counting2, 2];
        Hello.Three = array[counting2, 3];
        Hello1.Add(Hello);

    }

change your code as below itwill work. 更改您的代码如下所示将工作。 You need to instantiate the object inside so that it will new every time 您需要在内部实例化对象,以便每次都是新的

        for (int i = 0; i <= counting2;i++ )
        {
          Testing   Hello = new Testing();
            Hello.year = array[counting2, 0];
            Hello.One = array[counting2, 1];
            Hello.Two = array[counting2, 2];
            Hello.Three = array[counting2, 3];
            Hello1.Add(Hello);

        }

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

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