How to loop through array in C# 4.0?

What is the easiest way to loop through an array in C# 4.0 ?

eg.

foreach (var msg in MyObject.MyArray)
{
    Debug.WriteLine(DateTime.Now + ": " + msg.code);
}

Is there a more 'modern' way in C# 4.0 to do the above?

Answers


A loop is a loop. If you want to loop through an array, you probably won't find anything better than, well, a loop. Most of the other answers here create an unnecessary List just to use the syntactic sugar of the ForEach method, but it's still just a loop.

If you want a more modern frame of mind, don't ask "How can I loop over the array", but instead try to think what you're looping for. If, for example, you're constructing an output string from the members of the array, you could use string.Join, as @Selman22 mentions in the comments:

var output = string.Join(", ", MyObject.MyArray.Select(item => item.code);

or use the LINQ method Aggregate for more complicated aggregations, like aggregating the strings in reverse order:

MyObject.MyArray.Aggregate((output, nextItem) => nextItem.code + output);

If you're constructing new items based on that array values, use Select:

var statuses = MyObject.MyArray.Select(item => new StatusMessage(item.code));

And so forth. Don't try to reinvent the loop. Try to see where you don't actually need an explicit loop.


You could try something like this using Array.ForEach

string[] bar = {"1", "2", "3"};
Array.ForEach(bar, foo => Debug.WriteLine(DateTime.Now + ": " + foo));

So for your example it would be

Array.ForEach(MyObject.MyArray, msg => Debug.WriteLine(DateTime.Now + ": " + msg.code));

Its more about readability than being modern. You can use List.ForEach, but it is arguable whether this adds value:

MyObject.MyArray
        .ToList()
        .ForEach(msg => Debug.WriteLine("{0}:{1}", DateTime.Now, msg.code));

If you are looking to stick strictly to C# 4.0, then the answer is no, there is no more elegant way than what you are currently doing. The C# 4.0 spec seems to have gone AWOL (it's morphed into the C# 5.0 reference) but let me refer you to the closest thing I can find which is the C# reference for VS2010 (which pretty much coincides with 4.0).

However as a few other answers have pointed out there are some nice selection and iteration constructs built into LINQ, while they might be overkill for a simple loop they can be very nice for isolating out partial lists or for processing larger lists (especially when used in conjunction with PLINQ).


There are few ways, I listed those which are most relevant with some briefing:

var items = new[] {"ItemA", "ItemB", "ItemC", "ItemD", "ItemE"};

//option 1 - most intuative.
foreach (var item in items)
{
    Console.WriteLine(item);
    //other instructions of the iteration..
}

//option 2 - full control over the iterator.
for (var index = 0; index < items.Length; index++)
{
    var item = items[index];
    Console.WriteLine(item);
    //other instructions of the iteration..
}

//option 3a - shortest, modern.. but also less efficient due to the casting.
items.ToList().ForEach(Console.WriteLine);

//option 3b - same as 3a but can have more instructions inside..
items.ToList().ForEach(item =>
{
    Console.WriteLine(item);
    //other instructions of the iteration..
});

Using LINQ:

MyObject.MyArray.Select(x => String.Format("{0}: {1}", DateTime.Now,x.code)).ToList().ForEach(Debug.WriteLine)

Need Your Help

grabbing members from structs

ruby struct

I want to be able to iterate through some xml i'm using structs and I want to be able to grab the members from them after adding them to an array, is the way i'm doing it wrong?

Simplify static Select statement by removing unions

sql tsql sql-server-2012

I want to define values statically inside my query, not using any table.