Link to home
Start Free TrialLog in
Avatar of Moti Mashiah
Moti MashiahFlag for Canada

asked on

c# foreach loop

Hi Guys,

I'm wondering why the method I wrote return the same item.
Here is my scenario:
First, I'm querying items from the database using linq:
 var retend = (from a in rmdb.TenderEntries
                          join b in rmdb.Tenders
                          on a.TenderID equals b.ID
                          where a.TransactionNumber == transn
                          select new Tendermodel
                          {
                              Description = b.Description,
                              Displeyorder = b.DisplayOrder,
                              Amount = a.Amount,
                              Amountforign = a.AmountForeign
                          }).ToList();

Open in new window

 

I'm getting the item just fine no issue, but when I'm looping through the items the return comes with lets say two items as identical items:
Here is my foreach loop:
List<JournalModel> lstadd = new List<JournalModel>();
            foreach (var cur in retend)
            {
                jr.Payhchangedesc = cur.Description + " " + "Tendered";
                jr.Returncurent = cur.Amount;
                jr.Returncurent = cur.Amountforign;
                lstadd.Add(jr);
            }

            return lstadd;

Open in new window


The return lstadd - return the same item.
Let's say I got two item from the database which is coming just fine and then it goes to loop it will return 2 items but just the last one it will return twice.

What am I doing wrong here.:)
Avatar of Fernando Soto
Fernando Soto
Flag of United States of America image

Create a new instance of a type of what ever type Jr is.
Avatar of Moti Mashiah

ASKER

Actually, I did.
The instance
List<JournalModel> lstadd = new List<JournalModel>();
it is actually the jr object.
I hope I understood what I meant.
You need to create a new one each time through the loop.
like:

JournalModel jr = new JournalModel();
 List<JournalModel> lstadd = new List<JournalModel>();
         
            foreach (var cur in retend)
            {
                jr.Payhchangedesc = cur.Description + " " + "Tendered";
                jr.Returncurent = cur.Amount;
                jr.Returncurent = cur.Amountforign;
                lstadd.Add(jr);
            }

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Fernando Soto
Fernando Soto
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Fernanado, YOU ARE THE BEST.

I feel soo stupid sometimes LOL.. I was trying to create new instance from out of the loop.
Not a problem Moti, glad to have helped.

By the way I feel that way sometimes.