LINQ查询具有2个集合的对象

时间:2012-07-11 21:43:27

标签: linq asp.net-mvc-4

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

如何使用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);

1 个答案:

答案 0 :(得分:0)

而不是循环遍历foreach FilterGroup,您可以抓住第一个Filters的{​​{1}}:

FilterGroup