Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-mvc/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在foreach循环中显示特定列表项_C#_Asp.net Mvc_List_Razor - Fatal编程技术网

C# 在foreach循环中显示特定列表项

C# 在foreach循环中显示特定列表项,c#,asp.net-mvc,list,razor,C#,Asp.net Mvc,List,Razor,我试图显示添加到列表中的第二个元素。该列表填充在名为HomeController的控制器中: 列表元素添加到HomeController中,在foreach循环内。它们是从XML文件中获取的 tagsGroup.Add(... { Name = node.Attributes["Name"].Value, Label = node.Attributes["Label"].Value, Description = node.Attributes["Description"]

我试图显示添加到列表中的第二个元素。该列表填充在名为HomeController的控制器中:

列表元素添加到HomeController中,在foreach循环内。它们是从XML文件中获取的

tagsGroup.Add(...
{
    Name = node.Attributes["Name"].Value,
    Label = node.Attributes["Label"].Value,
    Description = node.Attributes["Description"].Value
});
然后,在我看来,我尝试获取一个特定的列表元素,如下所示:

<table class="table" id="container_attribute_group_secondary">
    <tr>
        <th>Name</th>
        <th>Label</th>
        <th>Description</th>
    </tr>

@foreach(myApp.Controllers.HomeController.TagsModel.TagsGroup.tagsGroup in Model.TagsGroup)
{
    <tr>
        <td>@tagsGroup.Name.[1]</td>
        <td>@tagsGroup.Label.[1]</td>
        <td>@tagsGroup.Description.[1]</td>
    </tr>
}

我可能把事情搞混了,因为我对列表和数组有些生疏,所以我希望有人能解释我出了什么问题,我应该怎么做

如果只需要显示添加到列表中的第二个元素,则不需要循环。删除foreach循环并简单地使用index,但由于TagsGroup是IENumerable,并且IENumerable接口不包含索引器,因此可以使用如下内容:

if (1 < @Model.TagsGroup.Count())
{
    <tr>
        <td>@Model.TagsGroup.ElementAt(1).Name</td>
        <td>@Model.TagsGroup.ElementAt(1).Label</td>
        <td>@Model.TagsGroup.ElementAt(1).Description</td>
    </tr>
}

也不是说我添加了一个检查来处理索引超出范围的错误,这对于IEnumerable中只有一个项的情况非常有用。

只需从每个项中删除[1]。foreach给您一个tagsgroup对象,您使用索引器[]查看每个字符串,而不是完整的属性。如果foreach可能会混淆我的问题,我只想显示一个字符串。如果没有foreach,我无法访问值,我正在尝试替换它,一旦我这样做,我将编辑帖子。如果IEnumerable中只有一项,您希望发生什么?是的,循环是不必要的。我尝试使用它,但它给了我一个错误,即无法将带[]的索引应用于“System.Collections.Generic.IENumerable”类型表达式的表达式。我已经编辑了这篇文章,不习惯发布问题,有时我会忘记一些细节。@BlindRoach因为IEnumerable界面不包含索引器,所以可以使用ElementAt。检查我的最新答案,就这样!谢谢您的帮助。@BlindRoach如果您需要为标记组编制索引,您应该考虑将其更改为列表而不是列表IEnumerable@S.Akbari当我问这个问题时,我没有特权,看到我的选票消失,即使他们说他们后来加入了,也有点恼人。好了
if (1 < @Model.TagsGroup.Count())
{
    <tr>
        <td>@Model.TagsGroup.ElementAt(1).Name</td>
        <td>@Model.TagsGroup.ElementAt(1).Label</td>
        <td>@Model.TagsGroup.ElementAt(1).Description</td>
    </tr>
}