当我们使用反向和排序方法时,为什么在数组中使用循环 [英] Why using loop in array when we use reverse and sort methods

查看:65
本文介绍了当我们使用反向和排序方法时,为什么在数组中使用循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

实际上我很困惑,在使用Array.Sort和Array.Reverse方法时,foreach和for循环在数组中的用途是什么。

每个和for循环使用的概念是什么。



例如

Actually i am very confused that what is the use of foreach and for loop in array while using Array.Sort and Array.Reverse method.
What is the concept behind using for each and for loop.

Eg

 int[] arr={2,4,6,1,3,9};
 int a=arr.Length;
 foreach(int i in arr)
{
   Console.WriteLine(i);
   Array.Sort(arr);
}

推荐答案

更好地阅读本文:http://csharp-station.com/Tutorial/CSharp/Lesson04 [ ^ ]
Better read this article: http://csharp-station.com/Tutorial/CSharp/Lesson04[^]


如果你想知道for和foreach之间的区别,你可以认为for为循环计数器而foreach循环通过集合中的元素。



请参考:

- for [ ^ ]

- foreach [ ^ ]



关于代码块,目前还不清楚为什么哟你有变量a存储数组的长度。你似乎没有在任何地方使用它。



此外,数组的排序是在每次迭代中完成的,但是数组的内容永远不会改变,为什么?



实际发生了什么,在第一次迭代中你打印出数组中的第一个元素是2.之后你对数组进行排序并打印排序后的第二个元素再次是2.这意味着你不打印所有元素,因为1从不打印。



应该在迭代之前进行排序吗?
If you''re wondering the difference between for and foreach, you can think the for as looping a counter whereas foreach loops through elemenents in a collection.

Please refer to:
- for[^]
- foreach[^]

About the code block, it''s unclear why you have the variable a which stores the length of your array. You don''t seem to use it anywhere.

Also the sorting of the array is done in each iteration but the contents of the array never changes, why?

What actually happens, in the first iteration you print the first element in the array which is 2. After that you sort the array and print the second element which after sorting is again 2. This means that you don''t print all the elements since 1 is never printed.

Should the sort be before the iteration?


这篇关于当我们使用反向和排序方法时,为什么在数组中使用循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆