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

How to retrieve all values from a foreach loop C#?

I am developing a JavaScript calendar based system to display dates for events in .Net Core and the issue I am having is iterating through the foreach loop and the last value is the only value that is displaying on my calendar , controller code as follows:

    public IActionResult Calendar()
    {
        var dateList = _context.Tasks.Select(x => x.DateAllTaskCompleted != null ? x.DateAllTaskCompleted.Value.ToString("yyyy-MM-dd") : null).ToList();
        var jsonDate="";

        foreach (var item in dateList)
        {
            if (item != null)
            {
                // TODO: Display all dates

                jsonDate = JsonSerializer.Serialize(item);
            }
        }
        ViewData["Date"] = jsonDate;

        return View();
    }

What solutions or adjustments can I make ?

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 :

Your code does not work because you are overriding jsonDate in each loop iteration. If you want to retrieve all dates you will need to declare, for example, jsonDates as list, and then to append to list in each iteration. Something like this:

public IActionResult Calendar()
{
    var dateList = _context.Tasks.Select(x => x.DateAllTaskCompleted != null ? x.DateAllTaskCompleted.Value.ToString("yyyy-MM-dd") : null).ToList();
    List<string> jsonDates = new List<string>();

    foreach (var item in dateList)
    {
        if (item != null)
        {
            // TODO: Display all dates

            jsonDates.Add(JsonSerializer.Serialize(item));
        }
    }
    ViewData["Date"] = jsonDates;

    return View();
}
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