C#新手:找出在foreach块索引 [英] C# newbie: find out the index in a foreach block

查看:181
本文介绍了C#新手:找出在foreach块索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个foreach块,我想绘制出微量调试目的在foreach内步骤的索引。作为一个C#新手我做如下:

I have a foreach block where I want to plot out for trace-debug purposes the index of the step inside the foreach. As a C# newbie I do it as follows:

int i = 1;

foreach (x in y)
{
    ... do something ...
    WriteDebug("Step: "+i.ToString());
    i++;
}



我不知道是否有什么办法让当前步骤的指数值,而不。明确创建用于此用途的变量

I wondered if there's any way to get the value of the current step's index without explicitly creating a variable for that purpose.

编辑:为了澄清,我显然熟悉的for循环的选项,但它不是一个数组我要去通过而是一个无序集合。究其原因,编号是仅仅为了出现在调试水平,没有别的进步的目的。

To clarify, I'm obviously familiar with the option of a for loop, however it's not an array I'm going through but rather an unordered collection. The reason for the numbering is just for the purpose of showing progress in the debug level and nothing else.

推荐答案

没有,有并非如此。

这是一个实例,你最好使用一个基本的for循环

This is an instance where you're better off using a basic for loop

for(int i = 0; i < y.Count; i++)
{
}

而不是每个循环

修改:为响应提问者澄清

如果您通过使用没有大小属性​​的枚举迭代(如长度或计数),那么你的做法是几乎一样澄清,你可以得到的。

If you're iterating through an enumerator with no size property (such as length or count), then your approach is about as clear as you can get.

二修改结果
给了我能选择的话我会选择使用要做到这一点,这些天采取马克的回答。

Second Edit
Given me druthers I'd take Marc's answer using select to do this these days.

这篇关于C#新手:找出在foreach块索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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