Casey Crookston Casey Crookston - 1 month ago 4
C# Question

Filter a list in the view

I have a simple @foreach loop in a view that iterates over a list:

@foreach (var record in Model.ChangeOrder.Change_Order_Dash_List)
{
....
}


Works great! But, depending on a boolean in the model, I may need to filter this list. This, I am having trouble figuring out. This is what I'm trying:

@{List<MCA.Models.ChangesVM.ChangeOrderInfo> Change_Order_Dash_List = new List<MCA.Models.ChangesVM.ChangeOrderInfo>();}

@if (Model.ViewChangeOrdersFromChart)
{
Change_Order_Dash_List = Model.ChangeOrder.Change_Order_Dash_List.Where(l => l.Implement_Date == Model.ViewChangeOrdersOnDate).ToList<MCA.Models.ChangesVM.ChangeOrderInfo>();
}
else
{
Change_Order_Dash_List = Model.ChangeOrder.Change_Order_Dash_List;
}


@foreach (var record in Change_Order_Dash_List )
{
....
}


But the results are weird. When I render the page, the list looks to be empty. No data is rendered to the screen. And if I set a breakpoint anywhere on the page, it is never hit.

What am I doing wrong?

Thanks!

Answer

Another (and IMO more simple) syntax to achieve this, is to merge the if condition into the Where using the || operator like this:

yourList.Where(l => !Model.ViewChangeOrdersFromChart || 
                    l.Implement_Date == Model.ViewChangeOrdersOnDate)

This will filter the list only when Model.ViewChangeOrdersFromChart is true. This way you don't need the if condition at all.