Home > Mobile >  Sorting collection which has list in it in ASP.NET
Sorting collection which has list in it in ASP.NET

Time:11-22

I am trying to sort a list with object which has another list as a property. However I am unable to sort in this property list.

    public class Activity
    {
        public int Activityid { get; set; }
        [Required(ErrorMessage = "Titel mangler")]
        public string? Title { get; set; }
        public string? ByWhom { get; set; }
        [Required(ErrorMessage = "Dato(er) mangler")]
        public List<Date>? Dates { get; set; }
        [Required(ErrorMessage = "Sluttid mangler")]
        public string? EndTime { get; set; }
        [Required(ErrorMessage = "Starttid mangler")]
        public string? StartTime { get; set; }
        [Required(ErrorMessage = "afdeling mangler")]
        public Department? Department { get; set; }
        [Required(ErrorMessage = "Lokale mangler")]
        public Room? Room { get; set; }
        public bool IsCancelled { get; set; } = false;

    }
    public class Date
    {
        public int DateID { get; set; }
        public DateTime date { get; set; }
    }

-> This is my attempt, the SelectedDate comes from another view

        [HttpPost]
        public ActionResult PreviewScreen(DateTime SelectedDate)
        {

            ViewBag.Departments = departmentRepository.Collection;
            return View(activityRepository.Collection.Include(d => d.Dates.Where(da => da.date == SelectedDate)));
        }
@model IQueryable<Activity>

<form asp-action="PreviewScreen" method="post">


<div>
    <select name="DepartmentID" id="input" required>
        @foreach (Department d in ViewBag.Departments)
        {
            <option value="@d.DepartmentID">@d.DepartmentName</option>
        }
    </select>
</div>

<div>
    <input name="SelectedDate" type="date" />
</div>

    <button type="submit">Vis</button>

</form>

@if (Model != null) 
{
    foreach (Activity a in Model)
    {
        <p>@a.Title</p>
    }
}

The problem is in the PreviewScreen method, with the return view, the attempt i have done is not working. It returns the whole list and doesn't sort with the selected date. Any help is appreicated!

CodePudding user response:

Update your LINQ expression similar to below.

return View(activityRepository.Collection.Where(d => d.Dates.Any(da => da.date == SelectedDate)));

This should help you to filter List<Activity> with items having current date in any of the items in List<Date> with in Activity.

Also refer to C# Linq where list in list

  • Related