对于foreach (var c in s),在循环中,如何随时知道c是s中的第几个元素,也就是c元素在s中的下标(位置)是几

zcdg909 2009-02-04 08:10:18
对于foreach (var c in s),在循环中,如何随时知道c是s中的第几个元素,也就是c元素在s中的下标(位置)是几
...全文
893 16 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
16 条回复
切换为时间正序
请发表友善的回复…
发表回复
wangzh2006 2009-02-05
  • 打赏
  • 举报
回复
可以用Array.IndexOf()获得位置
wwwspider001 2009-02-04
  • 打赏
  • 举报
回复
个人感觉foreach的本意就是遍历,而不关心下标

如果需要就要自己计数
heart_string 2009-02-04
  • 打赏
  • 举报
回复

for(int i=0;i<arr3.count;i++)
{
/////你要的索引
Console.WriteLine(i);
}
HDNGO 2009-02-04
  • 打赏
  • 举报
回复
http://discuss.joelonsoftware.com/default.asp?dotnet.12.612943.11

A foreach uses the IEnumerator interface, which has a Current property, and MoveNext and Reset methods. So there's not even the concept of an index in it. (Also, there's no guarantee what order you're enumerating in.) You'll need to either do your own counting, or use a for loop instead if the collection can take an index.
freewind0521 2009-02-04
  • 打赏
  • 举报
回复
foreach语句只能另加index了
流年岁月 2009-02-04
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 ojlovecd 的回复:]
C# code
int[] arr3 = { 4, 5, 6, 6, 7, 2, 5, 6 };
int index = 0;
foreach (var c in arr3)
Console.WriteLine(index++);
[/Quote]
这个行
7年 2009-02-04
  • 打赏
  • 举报
回复
定义起始位置,+1就好了。
caorenlong 2009-02-04
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 ojlovecd 的回复:]
C# code
int[] arr3 = { 4, 5, 6, 6, 7, 2, 5, 6 };
int index = 0;
foreach (var c in arr3)
Console.WriteLine(index++);
[/Quote]
正解
我姓区不姓区 2009-02-04
  • 打赏
  • 举报
回复

int[] arr3 = { 4, 5, 6, 6, 7, 2, 5, 6 };
int index = 0;
foreach (var c in arr3)
Console.WriteLine(index++);

pennymay 2009-02-04
  • 打赏
  • 举报
回复
那自己写个CLASS,
一个记INDEX,一个记数
zcdg909 2009-02-04
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 ojlovecd 的回复:]
C# code
int[] arr3 = { 4, 5, 6, 6, 7, 2, 5, 6 };
int index = 0;
foreach (var c in arr3)
Console.WriteLine(index++);
[/Quote]

不另外定义计数变量index,List<>就没有直接的属性或方法记录循环当前下标吗
sushou2009 2009-02-04
  • 打赏
  • 举报
回复
正解一楼~~
ChrisAK 2009-02-04
  • 打赏
  • 举报
回复
1.另弄一个变量计数.
2.用for改写.
vrhero 2009-02-04
  • 打赏
  • 举报
回复
虽然可以自己加索引变量...但是需要索引器就不应该用foreach应该用for...
kofkyo 2009-02-04
  • 打赏
  • 举报
回复
1楼正解
sphinger 2009-02-04
  • 打赏
  • 举报
回复
恩,貌似是这样地

111,098

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • AIGC Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧