开发者

Can I iterate through an array in C# using something like a foreach [closed]

It开发者_如何学Python's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 11 years ago.

I would like to do something like a foreach on an array of strings. I know I can do it with a for loop and incrementing but just wondering if there is something similar to the foreach:

foreach (var test in testlist)

Thanks


Yes, like this

string[] arr = {"a", "aa", "aaa"};

foreach(string item in arr)
{
    Console.WriteLine("array element: " + item);
}


Array types derive from the System.Array class. This is its declaration:

public abstract class Array : ICloneable, IList, ICollection, 
    IEnumerable, IStructuralComparable, IStructuralEquatable
{
    // etc..
}

It implements IEnumerable, that means that the foreach statement is supported.


The example you gave is correct.

string[] mystrings = GetArrayOfStrings();
foreach(String s in mystrings) {

}


Edit: If testlist is an array, then you aready have the answer, since an array implements IEnumerable.

foreach (var test in testlist)
{

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜