C# 无法反转列表<;T>;内foreach
我有一个C# 无法反转列表<;T>;内foreach,c#,C#,我有一个列表,我需要将其反转,因此我尝试: foreach (Round round in Competition.Rounds.Reverse()) { } 这将返回以下错误: the foreach statement can not work with variables of type 'void' because 'void' does not contain a public instance definition for 'GetEnumerator' 如何解决此问
列表
,我需要将其反转,因此我尝试:
foreach (Round round in Competition.Rounds.Reverse())
{
}
这将返回以下错误:
the foreach statement can not work with variables of type 'void'
because 'void' does not contain a public instance definition for 'GetEnumerator'
如何解决此问题?反向返回无效,而是执行以下操作:
Competition.Rounds.Reverse();
foreach (Round round in Competition.Rounds){...}
或者,如果您不想修改竞赛。回合
,则使用可枚举。反向(…)
:
或效率较低的替代方案:
foreach (String round in Competition.Rounds.ToArray().Reverse()){...}
反向返回无效,而是执行以下操作:
Competition.Rounds.Reverse();
foreach (Round round in Competition.Rounds){...}
或者,如果您不想修改竞赛。回合
,则使用可枚举。反向(…)
:
或效率较低的替代方案:
foreach (String round in Competition.Rounds.ToArray().Reverse()){...}
有两种
反向方法需要考虑:
- instance方法反转原位列表,但具有
void
返回类型
- 扩展方法不修改数据源,但返回数据的反向“视图”
编译器只在耗尽实例方法后才查找扩展方法-因此在本例中,它绑定到List.Reverse()
方法。。。这就是它无法编译的原因。(您不能迭代void
)
如果要修改列表,只需单独调用该方法:
Competition.Rounds.Reverse();
foreach (Round round in Competition.Rounds)
{
...
}
如果不想修改列表,最简单的方法可能是调用Enumerable.Reverse
直接:
foreach (Round round in Enumerable.Reverse(Competition.Rounds))
{
...
}
或者,您可以有效地“丢失”列表的编译时类型,例如:
// Important: don't change the type of rounds to List<Round>
IEnumerable<Round> rounds = Competition.Rounds;
foreach (Round round in rounds.Reverse())
{
...
}
//重要提示:不要将轮次类型更改为列表
IEnumerable rounds=竞争。rounds;
foreach(一轮接一轮。Reverse())
{
...
}
有两种方法需要考虑:
- instance方法反转原位列表,但具有
void
返回类型
- 扩展方法不修改数据源,但返回数据的反向“视图”
编译器只在耗尽实例方法后才查找扩展方法-因此在本例中,它绑定到List.Reverse()
方法。。。这就是它无法编译的原因。(您不能迭代void
)
如果要修改列表,只需单独调用该方法:
Competition.Rounds.Reverse();
foreach (Round round in Competition.Rounds)
{
...
}
如果不想修改列表,最简单的方法可能是调用Enumerable.Reverse
直接:
foreach (Round round in Enumerable.Reverse(Competition.Rounds))
{
...
}
或者,您可以有效地“丢失”列表的编译时类型,例如:
// Important: don't change the type of rounds to List<Round>
IEnumerable<Round> rounds = Competition.Rounds;
foreach (Round round in rounds.Reverse())
{
...
}
//重要提示:不要将轮次类型更改为列表
IEnumerable rounds=竞争。rounds;
foreach(一轮接一轮。Reverse())
{
...
}
在您的问题中,您的意思是“我需要反转”还是“我需要以相反的顺序迭代,而不修改列表”。在您的问题中,您的意思是“我需要反转”还是“我需要以相反的顺序迭代,而不修改列表”。