在视图中使用Contains()检查IEnumerable

Sti*_*ian 0 c# asp.net-core-mvc

我正在尝试渲染一个链接列表,图标应该根据是否找到项目ID而改变IEnumerable.

到目前为止,这是我观点的相关部分:

@{
if (product.InFrontPages.Contains(item.ParentCategory.Id))
    {
        <span class="glyphicon glyphicon-checked"></span>
    }
    else
    {
        <span class="glyphicon glyphicon-unchecked"></span>
    }
}
Run Code Online (Sandbox Code Playgroud)

这会导致编译时错误:

'IEnumerable'不包含'Contains'的定义,并且最好的扩展方法重载'ParallelEnumerable.Contains(ParallelQuery,int)'需要一个'ParallelQuery'类型的接收器

我想我可能想要实现这个问题的公认答案,但我还没想出怎么做.当他建议实现通用接口时,我不明白Jon的意思.

涉及的视图模型:

public class ViewModelProduct
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string Info { get; set; }
    public decimal Price { get; set; }
    public int SortOrder { get; set; }
    public IEnumerable<FrontPageProduct> InFrontPages { get; set; }
    public IEnumerable<ViewModelCategoryWithTitle> Categories { get; set; }
}

    public class ViewModelProductCategory
{
    public int Id { get; set; }
    public int? ParentId { get; set; }
    public string Title { get; set; }
    public int SortOrder { get; set; }
    public string ProductCountInfo
    {
        get
        {
            return Products != null && Products.Any() ? Products.Count().ToString() : "0";
        }
    }
    public IEnumerable<FrontPageProduct> FrontPageProducts { get; set; }
    public ViewModelProductCategory ParentCategory { get; set; }
    public IEnumerable<ViewModelProductCategory> Children { get; set; }
    public IEnumerable<ViewModelProduct> Products { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 6

问题是ContainsLINQ方法没有你期望的签名 - 你试图检查是否IEnumerable<FrontPageProduct>包含int......它不能,因为它只有FrontPageProduct引用.

我怀疑你想要的东西:

if (product.InFrontPages.Any(page => page.Id == item.ParentCategory.Id)
Run Code Online (Sandbox Code Playgroud)

(我可能会使用条件运算符而不是if语句,但这是另一回事.)