我有一个类SearchOutput,其属性为FilterGroups。在这种情况下,IEnumerable<FilterGroup>是两个同时包含属性FilterGroupsFilters的对象的列表。这两个对象拥有不同的过滤器和不同的名称(“品牌”和“颜色”)。

我如何使用LINQ仅获得那些对象的过滤器之一?

这是视图中的代码:

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


我的课程:

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


我的控制器的动作:

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

最佳答案

而不是遍历foreach FilterGroup,您可以使用以下方法获取第一个FiltersFilterGroup

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

09-07 00:42