【问题标题】:check if list element is equal to any other element in list using for-loop使用for循环检查列表元素是否等于列表中的任何其他元素
【发布时间】:2014-07-10 13:35:34
【问题描述】:

我正在上这门课:

public class SortOrderModel
{
    public string IdSort { get; set; }
    public List<ContentPage> ContentPages { get; set; }
}

上面有listpropery的类就是这个类的一个列表:

public class ContentPage
{
public string Id { get; set; }
public string ParentReference { get; set; }
public string Url { get; set; }
public int SortOrder { get; set; }
public string Title { get; set; }
}

我有这个 for 循环,女巫有类 SortOrderModel 作为视图的@model。 我现在要检查第一个 if 语句:如果 Model.ContentPages[i].ParentReference 等于整个 Model.ContentPages-list 中的 Any Url-propery。我试过很多方法,但不知道如何解决。

            for (int i = 0; i < Model.ContentPages.Count; i++)
            {
            <ul>
                    if (Model.ContentPages[i].ParentReference == TODO) <-------
                    {
                        <li style="padding-left: 80px;">@Model.ContentPages[i].Title @Html.TextBoxFor(o => Model.ContentPages[i].SortOrder, new { @class = "sortBox" })</li>

                    }
                    else
                    {
                        <li style="padding-left: 40px;">@Model.ContentPages[i].Title @Html.TextBoxFor(o => Model.ContentPages[i].SortOrder, new { @class = "sortBox" })</li>

                    }

            </ul>
            }

【问题讨论】:

  • 您应该标记适当的语言。此外,如果这是 asp.net MVC,也有一个特定的标签。
  • 对不起,我是新手...现在添加了一些标签。谢谢@crashmstr

标签: c# asp.net-mvc for-loop


【解决方案1】:

试试:

if (Model.ContentPages.Any(m => m.Url == Model.ContentPages[i].ParentReference))

不过,请注意延迟加载和多次枚举。如果尚未查询所有项目,则每次调用不同的变体时,CountAny 之类的东西都会导致新的查询。但是,如果您首先将 Model.ContentPages 转换为列表,那么计数和其他 LINQ 查询将在同一个已查询的内存中列表上运行。例如:

var contentPages = Model.ContentPages.ToList();
for (int i = 0; i < contentPages.Count(); i++)
{
    <ul>
        if (contentPages.Any(m => m.Url == contentPages[i].ParentReference))
        {
            ...

【讨论】:

  • 感谢您的回复。它可以满足我的要求。所以谢谢!但是在运行代码时,a 发现这是我想做的其他事情。不过还是谢谢
  • 再次感谢您的回答!但就像我说的,我发现我是为了别的东西。所以我发布了一个关于我想要实现的目标的新问题。如果你愿意,请看一下! =) link
猜你喜欢
  • 2022-11-04
  • 2020-08-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-01
  • 2021-10-30
相关资源
最近更新 更多