3

I have a class SearchOutput which has a property FilterGroups that's an IEnumerable<FilterGroup>. In this instance, the FilterGroups is a list of two objects both holding the properties Filters and Name. Both objects hold different filters and a different name ("Brands" and "Color").

How would I get just one of those object's filters using LINQ?

Here is my code in the view:

@foreach(var filterGroup in Model.FilterGroups)
{
    foreach(var filter in filterGroup.Filters.Take(10))
    {
        <li>
            <a href="javascript:void(0)"><span class="tickMark"></span><strong>@filter.Name<span>(@filter.ProductCount)</span></strong></a>
        </li>
    }
}
My classes:
public sealed class Filter
{
    public string Id { get; set; }

    public bool IsChecked { get; set; }

    public string Name { get; set; }

    public int ProductCount { get; set; }
}

[DebuggerDisplay("{Name}")]
public sealed class FilterGroup
{
    public IEnumerable<Filter> Filters { get; set; }

    public string Name { get; set; }
}

public sealed class SearchOutput
{
    ...
    public IEnumerable<FilterGroup> FilterGroups { get; set; }
    ...
}
My controller's Action:
var searchOutput = new SearchOutput
{
    Layout = layout,
    ActionUrl = "/shop/{0}/{1}".FormatForInvariantCulture(input.Slug, input.Id),
    BreadboxSection = breadboxSection,
    Breadcrumbs = breadcrumbLinks,
    CurrentPage = page,
    FilterGroups = filterGroups,
    Name = isStorefront ? breadcrumbLinks.Last().Text : string.Empty,
    NextPageUrl = BuildNextPageUrl(products, input, page, selections, sort),
    PreviousPageUrl = BuildPreviousPageUrl(input, page, selections, sort),
    Products = productList,
    Selections = selections,
    SpotlightFilters = spotlightFilters,
    TotalPages = BuildTotalPages(products),
    UpcomingShows = UpcomingShows
};

if(isStorefront)
    return View("~/Views/" + RenderViewType + "/Store.cshtml", searchOutput);
else
    return View("~/Views/" + RenderViewType + "/Search.cshtml", searchOutput);
4

1 回答 1

0

而不是通过 foreach 循环,FilterGroup您可以使用以下方法获取Filters第一个FilterGroup

@foreach(var filter in Model.FilterGroups.First(x => x.Name == "Brands").Filters.Take(10))
{
    <li>
        <a href="javascript:void(0)"><span class="tickMark"></span><strong>@filter.Name<span>(@filter.ProductCount)</span></strong></a>
    </li>
}

@foreach(var filter in Model.FilterGroups.First(x => x.Name == "Color").Filters.Take(10))
{
    <li>
        <a href="javascript:void(0)"><span class="tickMark"></span><strong>@filter.Name<span>(@filter.ProductCount)</span></strong></a>
    </li>
}
于 2012-07-11T22:23:25.840 回答