简体   繁体   English

如何在C#中动态添加项目到列表

[英]How to add items to list in c# dynamically

Hi I am developing one mvc4 application. 嗨,我正在开发一个mvc4应用程序。 I came across one scenario where i want to add items ti list. 我遇到一种情况,我想在列表中添加项目。 I have one foreach loop inside that i have one list. 我有一个foreach循环,里面有一个列表。 This is my code. 这是我的代码。

foreach (var indId in myuploadId)
{
   List<emailClass> getemailDetails = objBAL.getemailDetails(indId);
   List<emailClass> obj = new List<emailClass>();
   obj.AddRange(getemailDetails);
}

This is my code snippet. 这是我的代码段。 getemailDetails method will take some data from database and add it to obj list. getemailDetails方法将从数据库中获取一些数据并将其添加到obj列表中。 On second iteration of foreach loop it gets corresponding data from database and add it to obj but here I am facing problem. 在foreach循环的第二次迭代中,它从数据库中获取了相应的数据并将其添加到obj,但是在这里我面临着问题。 Whenever i add second item to obj my first item gets disappear. 每当我将第二项添加到obj时,我的第一项就会消失。 Can someone tell me how can i retain information in list? 有人可以告诉我如何在列表中保留信息吗? Thank you. 谢谢。

You need to move the declaration of the lists outside of the loop. 您需要将列表的声明移出循环。 At the moment on each loop a new list is created and the old one is lost. 此刻在每个循环上都会创建一个新列表,而旧列表会丢失。

Change your code to look like the below, see that the lists are outside the loop so they get re-used each time rather than replaced. 将代码更改为如下所示,请注意列表不在循环内,因此每次都可以重复使用它们,而不是替换它们。

List<emailClass> getemailDetails = new List<emailClass>();
List<emailClass> obj = new List<emailClass>();

foreach (var indId in myuploadId)
{
    getemailDetails = objBAL.getemailDetails(indId);
    obj.AddRange(getemailDetails);
}

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

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