How to use LINQ with a 2 dimensional array

前端 未结 5 1494
深忆病人
深忆病人 2020-12-21 08:38

I have a 2-dimensional byte array that looks something like this:

0 0 0 0 1

1 1 1 1 0

0 0 1 1 1

1 0 1 0 1

5条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-21 09:07

    Here is how I would do it. It's the same as others more or less, but without any Enumerable.Range (not that there is anything wrong with those (I use them all the time)...it just makes the code more indented in this case).

    This one also includes PLINQ stuff. TPL (async/await) wouldn't be suitable for this because it is computationally bound and TPL is better suited to I/O bound operations. Your code would end up executing sequentially if you used async/await rather than PLINQ. This is because async/await won't go parallel until the thread is released (and it can start the next task...which could then go parallel) and purely synchronous functions (such as CPU stuff) won't every actually await...they'll just run all the way through. Basically, it would finish the first thing in your list before it even started the next thing, making it sequentially executed. PLINQ explicitly starts parallel tasks and doesn't have this issue.

    //arry is your 2d byte array (byte[,] arry)
    var maxIndex = arry
        .Cast() //cast the entire array into bytes
        .AsParallel() //make the transition to PLINQ (remove this to not use it)
        .Select((b, i) => new // create indexes
            {
                value = b,
                index = i
            })
        .GroupBy(g => g.index / arry.GetLength(1)) // group it by rows
        .Select((g, i) => new
            {
                sum = g.Select(g2 => (int)g2.value).Sum(), //sum each row
                index = i
            })
        .OrderByDescending(g => g.sum) //max by sum
        .Select(g => g.index) //grab the index
        .First(); //this should be the highest index
    

    In terms of efficiency, you would probably get better results with your for loop. The question I would ask is, which is more readable and clear?

提交回复
热议问题