【问题标题】:Check IEnumerable using Contains() in a view在视图中使用 Contains() 检查 IEnumerable
【发布时间】:2018-02-07 18:33:56
【问题描述】:

我正在尝试呈现链接列表,图标应该会根据是否在 IEnumerable 中找到项目 ID 而发生变化。

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

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

这会导致编译时错误:

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

我想我可能想要实现the accepted answer to this question,但我还没有想出如何去做。当 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; }
}

【问题讨论】:

  • @mjwills 我添加了相关的视图模型。
  • @mjwills 我在.Count()? 上收到一个错误:“运算符?不能应用于 int 类型的操作数”。
  • 使用return Products?.Count().ToString() ?? "0";

标签: c# asp.net-core-mvc


【解决方案1】:

问题是 Contains LINQ 方法没有您期望的签名 - 您正在尝试检查 IEnumerable&lt;FrontPageProduct&gt; 是否包含 int... 它不能,因为它只有FrontPageProduct 参考资料。

我怀疑你想要类似的东西:

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

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

【讨论】:

    【解决方案2】:

    一种方法是使用 lamda 表达式。像这样的

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-21
      • 2019-09-07
      • 2015-05-12
      • 2011-03-20
      • 2016-10-26
      • 1970-01-01
      • 2015-09-05
      • 1970-01-01
      相关资源
      最近更新 更多