可以通过c#.net中的foreach循环访问锯齿状数组

时间:2016-12-11 13:12:23

标签: c# asp.net .net jagged-arrays

如何通过C#.net中的 foreach 访问参差不齐的数组?

  

怎么做呢?

2 个答案:

答案 0 :(得分:1)

class BoardViewController: UIViewController {
    let blackImage = UIImage(named: "blackImage")!
    let whiteImage = UIImage(named: "whiteImage")!
    @IBOutlet var squares: [UIImageView]!
    var recognizersAdded = false

    func setUpBoard() {
        for imageview in squares {
            if !recognizersAdded {
                let recognizer = UITapGestureRecognizer(target: self, action: #selector(squareTapped))
                imageview.addGestureRecognizer(recognizer)
                imageview.isUserInteractionEnabled = true
            }

            let tag = view.tag
            let row = tag / 10
            let col = tag % 10

            // Just for demo purposes, set up a checkerboard pattern
            if (row + col) % 2 == 0 {
                imageview.image = blackImage
            } else {
                imageview.image = whiteImage
            }
        }
        recognizersAdded = true
    }

    func squareTapped(recognizer: UIGestureRecognizer) {
        if let view = recognizer.view as? UIImageView {
            let tag = view.tag
            let row = tag / 10
            let col = tag % 10
            print("The view at row \(row), column \(col) was tapped")

            if view.image == blackImage {
                view.image = whiteImage
            } else {
                view.image = blackImage
            } 
        }
    }
}

输出:

int[][] jaggedArray = new int[][] 
{
    new int[] { 0, 1, 2 },
    new int[] { 3, 4 },
    new int[] { 5 }
};
foreach (int[] array in jaggedArray)
{
    foreach (int value in array)
    {
        Console.WriteLine(value.ToString());
    }
}

答案 1 :(得分:0)

您可以使用linq

foreach (int item in jaggedarray.SelectMany(i => i))
{
    // work with item
}