Niranjan Godbole Niranjan Godbole - 19 days ago 7
C# Question

How to add items to list in c# dynamically

Hi I am developing one mvc4 application. I came across one scenario where i want to add items ti list. I have one foreach loop inside that i have one list.
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. On second iteration of foreach loop it gets corresponding data from database and add it to obj but here I am facing problem. Whenever i add second item to obj my first item gets disappear. Can someone tell me how can i retain information in list? Thank you.

Answer

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