Moti Mashiah
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:
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:
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.:)
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();
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;
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.:)
Create a new instance of a type of what ever type Jr is.
ASKER
Actually, I did.
The instance
List<JournalModel> lstadd = new List<JournalModel>();
it is actually the jr object.
The instance
List<JournalModel> lstadd = new List<JournalModel>();
it is actually the jr object.
ASKER
I hope I understood what I meant.
You need to create a new one each time through the loop.
ASKER
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);
}
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Fernanado, YOU ARE THE BEST.
I feel soo stupid sometimes LOL.. I was trying to create new instance from out of the loop.
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.
By the way I feel that way sometimes.