简体   繁体   中英

Foreach doesn't add each item from foreach to ViewModel

I am sure I am just thinking about this far too much, but I am trying to get a list and everything works except for one thing. And I know why it's doing it, it's getting the last item of the foreach that is assigned to the outside of the loop and returning just that one item. But I want to to return ALL of them. What am I doing wrong?

var cheeses = _repository.GetAllYearSetupIds();
var gouda = new CollectionsManagementViewModel();
var yearSetupId = 0;
foreach(var cheddar in cheeses)
{
    yearSetupId = cheddar.YearSetupId;
    gouda = _repository.GetOverdueBalances(page, pageLength, yearSetupId, balancefilter, sort, direction == Constants.ascending, spreadsheetType);
    gouda.Title = title + " Management";
}      
return View("CollectionsManagement", gouda);

Currently, you are updating single instance of CollectionsManagementViewModel named gouda on each iteration in your loop. After the loop gouda will have the value from the last iteration.

You should create new instance of CollectionsManagementViewModel on each iteration and add this instance to the list of view models. Of course naming should be meaningful:

// list of models, because you want ALL of them
var managementModels = new List<CollectionsManagementViewModel>();
var setupIds = _repository.GetAllYearSetupIds();

foreach(var setupId in setupIds)
{
   // new model created for each setup id
   var managementModel = _repository.GetOverdueBalances(page, pageLength,
            setupId.YearSetupId, balancefilter,
            sort, direction == Constants.ascending,
            spreadsheetType);

   managementModel.Title = title + " Management";
   managementModels.Add(managementModel); // add model to list
}

// pass collection to view
return View("CollectionsManagement", managementModels);

Hi Hope following code may helpful for you

var cheeses = _repository.GetAllYearSetupIds();
var lstgouda = new  List<CollectionsManagementViewModel>();  //make a list
var yearSetupId = 0;
foreach(var cheddar in cheeses)
{

    var gouda = new  CollectionsManagementViewModel(); 
    yearSetupId = cheddar.YearSetupId;
    gouda = _repository.GetOverdueBalances(page, pageLength, yearSetupId, balancefilter, sort, direction == Constants.ascending, spreadsheetType);
    gouda.Title = title + " Management";
    lstgouda.add(gouda);  //add it to list
}      
return View("CollectionsManagement", lstgouda);

Thanks Karthik

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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