Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Blazor C# – Map and add to List while incrementing through List

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading