转换为foreach [英] Converting from for to foreach

查看:75
本文介绍了转换为foreach的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,



我是.net的新手,我有一个需要编写foreach循环的情况,但我并不完全清楚但是我写道for循环。任何人都可以帮我转换下面的代码到foreach吗?



以下是我的代码:



Hi All,

I am new to .net and i have a situation where need to write the foreach loop but i am not aware of it exactly but i wrote for loop. Can anyone help me converting the below code to foreach?

Below is my code:

List<Int32> multiObject = ((List<Int32>)favoriteDocumentsField.Value);
     for (int index = 0; index < multiObject.Count; index++) {
          Int32 docID = multiObject[index];
          Console.WriteLine("Artifact: {0} Field: {1} Value: {2}", employee.ArtifactID, favoriteDocumentsField.Name + " Object " + index, docID);
     }



任何帮助都将不胜感激。



我尝试过:



我尝试在谷歌搜索。我得到了直接的FOREACH循环示例并且使用但没有得到从for到foreach的转换。


Any help would be appreciated.

What I have tried:

I tried searching in google. I got the direct FOREACH loop examples and used but didn't get the conversion from the for to foreach.

推荐答案

未经测试



Untested

List<Int32> multiObject = ((List<Int32>)favoriteDocumentsField.Value);
     foreach (int docID in multiObject) {
          Console.WriteLine("Artifact: {0} Field: {1} Value: {2}", employee.ArtifactID, favoriteDocumentsField.Name, docID);
     }





我已经放弃了从WriteLine写入索引值,因为它不再存在。如果你真的想要那个索引值,你最好把它留作for循环。你可以将索引作为自己的变量并在foreach中增加它,但是当你可以将它保持为for循环时,没有必要这样做。



I've dropped writing the index value from your WriteLine as it no longer exists. If you really want that index value you're better leaving it as a for loop. You could have index as its own variable and increment it inside the foreach, but there is not point in doing that when you can keep it as a for loop instead.


这篇关于转换为foreach的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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