Can I iterate through an array in C# using something like a foreach [closed]
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)
{
}
精彩评论