Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/337.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# 无法反转列表<;T>;内foreach_C# - Fatal编程技术网

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())
{
...
}

在您的问题中,您的意思是“我需要反转”还是“我需要以相反的顺序迭代,而不修改列表”。在您的问题中,您的意思是“我需要反转”还是“我需要以相反的顺序迭代,而不修改列表”。