How do you loop through a multidimensional array?

后端 未结 7 1404
陌清茗
陌清茗 2021-01-03 19:50
foreach (String s in arrayOfMessages)
{
    System.Console.WriteLine(s);
}

string[,] arrayOfMessages is being passed in as a parameter

7条回答
  •  再見小時候
    2021-01-03 20:29

    A more functional approach would be to use LINQ, which I always find better than loops. It makes the code more maintainable and readable. The below given code snippet shows one of the solution using Method or Fluent LINQ syntax.

    string[,] arrayOfMessages = new string[3, 2] { { "Col1","I am message 1" }, { "Col2", "I am message 2" }, { "Col3", "I am message 3" } };
    var result = arrayOfMessages.Cast()
                                .Where((msg, index) => index % 2 > 0);
    
    foreach (var msg in result)
    {
        Console.WriteLine(msg);
    }
    

    LINQ extension methods are not available to multi-dimensional arrays since they do not implement IEnumerable interface. That's where Cast comes into picture. It basically casts the whole array into IEnumerable. In our case it will flatten out the multi-dimensional array into IEnumerable something like:

    { "Col1", "I am message 1", "Col2", "I am message 2", "Col3", "I am message 3" }
    

    You can also use OfType instead of Cast. The only difference between them is that in case of collections with mixed data types, while OfType ignores values which it is unable to cast, Cast will throw an InValidCastException.

    Next, all we need to do is to apply a LINQ operator that ignores (or filters out) values at even indices. So we use an overload of Where operator whose Func delegate is of the type Func, where TSource is each item in the collection, int is the index of the item in the collection and bool is the return type.

    In the above snippet, I used a lambda expression which evaluates each item index and returns true only when it is an odd number.

提交回复
热议问题