Home > Software engineering >  Blazor C# - Map and add to List while incrementing through List
Blazor C# - Map and add to List while incrementing through List

Time:02-03

I have currently written the following code in Blazor while attempting to populate and then return a list.

public async Task<IEnumerable<LocationDTO>> GetStuff(List<StuffDTO> stuff)
        {
            List<LocationDTO> locations = new List<LocationDTO>();

            stuff.ForEach(stuff=>
            {
                locations = _mapper.Map<IEnumerable<Location>, IEnumerable<LocationDTO>>(_db.table.Where(u => u.LocationNumber == stuff.Location.ToString()).Distinct()).ToList();
            });
            return locations;
        }

But while testing the code, I noticed that I was only getting one result. I carefully debugged and traversed through my code and loop, and discovered that everything in my "stuff" list that was passed through was correct. But I saw that my locations list was being overwritten with each loop. My guess was because it wasn't incrementing in the same way as a for loop, or because my syntax was possibly off? My question is, with the way I've written my code, can I add an index? Simply creating index variable and passing through again as below did not change the output:

public async Task<IEnumerable<LocationDTO>> GetStuff(List<StuffDTO> stuff)
        {
            int index = 0;
            List<LocationDTO> locations = new List<LocationDTO>();

            stuff.ForEach(stuff=>
            {
                locations = _mapper.Map<IEnumerable<Location>, IEnumerable<LocationDTO>>(_db.table.Where(u => u.LocationNumber == stuff.Location.ToString()).Distinct()).ToList();

                 index  
            });
            return locations;
        }

CodePudding user response:

public async Task<IEnumerable<LocationDTO>> GetStuff(List<StuffDTO> stuff)
    {            
        List<LocationDTO> locations = new List<LocationDTO>();

        stuff.ForEach(stuff=>
        {
            locations.AddRange(_mapper.Map<IEnumerable<Location>, IEnumerable<LocationDTO>>(_db.table.Where(u => u.LocationNumber == stuff.Location.ToString()).Distinct()).ToList());
             
        });
        return locations;
    }

You have to add to the list, instead of replacing it.

  • Related