Check IEnumerable using Contains() in a view

I'm trying to render a list of links, and the icon should change depending on wether the item Id is found within an IEnumerable or not.

This is the relevant part of my view so far:

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

This causes a compile time error:

'IEnumerable' does not contain a definition for 'Contains' and the best extension method overload 'ParallelEnumerable.Contains(ParallelQuery, int)' requires a receiver of type 'ParallelQuery'

I think I may want to implement the accepted answer to this question, but I haven't figured out how to do it. I don't understand what Jon means when he suggests implementing the generic interface.

The involved viewmodels:

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; }
}
Jon Skeet
people
quotationmark

The problem is that the Contains LINQ method doesn't have the signature you expect - you're trying to check whether an IEnumerable<FrontPageProduct> contains an int... it can't, because it only has FrontPageProduct references.

I suspect you want something like:

if (product.InFrontPages.Any(page => page.Id == item.ParentCategory.Id)

(I'd potentially use a conditional operator instead of an if statement, but that's a different matter.)

people

See more on this question at Stackoverflow