-4

Since C# is so flexible (due in part to its interpreted nature) I was wondering whether the following feature is readily available. Otherwise I will just roll my own.

I have a List<MyModel> which would be much easier/convenient to traverse with a nested loop:

for (col = 1 to lastCol)
    for (row = 1 to lastRow)
        scrutinize(row, col);

Addition: Perhaps I should use foreach across the columns?

Ondrej Tucny
  • 27,626
  • 6
  • 70
  • 90
Travis Banger
  • 697
  • 1
  • 7
  • 19
  • 3
    You may need to give more information on MyModel. – tofutim Jan 02 '14 at 21:17
  • 8
    1) C# is *not* an interpreted language. 2) The code you have posted is *not* C#. – Ondrej Tucny Jan 02 '14 at 21:18
  • 1
    What do you mean by traversing a `List` with a nested loop? Can you be more specific on what you want to achieve? Please do include code of your current solution. – Ondrej Tucny Jan 02 '14 at 21:20
  • Let's say that the properties are the TV manufacturers: and the rows the number of units sold each year. In need `for manufacturer = apple to zenith` – Travis Banger Jan 02 '14 at 21:23
  • 2
    **[XY Problem](http://meta.stackexchange.com/a/66378). What are you trying to do?** Post some additional code to clarify what is needed. – Federico Berasategui Jan 02 '14 at 21:25
  • I need to refer to each cell with an [x,y] pair. Let's say that I want to add all the sales of all the manufacturers. I am guessing that I should use `foreach` – Travis Banger Jan 02 '14 at 21:29
  • @OndrejTucny: "C# is not an interpreted language." Microsoft is working on a project to provide **compiled C#** – Travis Banger Jan 02 '14 at 21:42
  • 1
    Really unclear; **why** do you “need to refer to each cell with an [x,y] pair”? If you are starting with a list, what do x and y represent? – Dour High Arch Jan 02 '14 at 21:48
  • 3
    @TravisBanger You should rather read something about the terms *interpreted* and *interpreter*, *compiler*, *JIT*, etc. before making such claims. Otherwise you may sound funny. – Ondrej Tucny Jan 02 '14 at 21:50
  • @OndrejTucny is right. [C# is compiled into IL](http://stackoverflow.com/a/8837367/643085) – Federico Berasategui Jan 02 '14 at 21:54
  • @TravisBanger One more thing: Please **do not** repeat tags in question titles, which is a general consensus on Stack Overflow. Almost all your questions are spoiled like that. – Ondrej Tucny Jan 02 '14 at 21:56

1 Answers1

2

Answering your title question, you can break down one dimensional list into 2D array by using LINQ. For simple list of integers:

List<int> list = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8 };
var array =
list.Select((v, i) => new { Value = v, Index = i})
    .GroupBy(x => x.Index / 4, x => x.Value, (key,values) => values.ToArray())
    .ToArray();

and then you can access list elements by using two dimensional array.

Konrad Kokosa
  • 16,563
  • 2
  • 36
  • 58