473,915 Members | 7,703 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Referencing [,] element as [ ]?

I have a two-dimensional array with 6 x 7 elements. I'd like to be able to
reference the elements sequentially, as if the rows were laid end-to-end. I
know the Array.Length property will give me the length of the array as 42,
but I'd like to be able to reference specific elements. For example, I'd
like to be able to reference foo[3,2] as foo[24].

Is there any way to do this natively in C#? Right now I'm using a conversion
function that takes an index and returns a cell reference. I'd like to
eliminate the function, if I can. Thanks in advance.

--
David Veeneman
Foresight Systems
Jan 19 '06 #1
14 1507
Something like this?

foo[Math.Floor(24/7),24%7] // foo[24]

In C you could fo what you say, but they were just downright nasty memory
overruns that happened to work...

"David Veeneman" <da****@nospam. com> wrote in message
news:%2******** *******@TK2MSFT NGP12.phx.gbl.. .
I have a two-dimensional array with 6 x 7 elements. I'd like to be able to
reference the elements sequentially, as if the rows were laid end-to-end. I
know the Array.Length property will give me the length of the array as 42,
but I'd like to be able to reference specific elements. For example, I'd
like to be able to reference foo[3,2] as foo[24].

Is there any way to do this natively in C#? Right now I'm using a
conversion function that takes an index and returns a cell reference. I'd
like to eliminate the function, if I can. Thanks in advance.

--
David Veeneman
Foresight Systems

Jan 19 '06 #2
David Veeneman wrote:
I have a two-dimensional array with 6 x 7 elements. I'd like to be able to
reference the elements sequentially, as if the rows were laid end-to-end. I
know the Array.Length property will give me the length of the array as 42,
but I'd like to be able to reference specific elements. For example, I'd
like to be able to reference foo[3,2] as foo[24].

Is there any way to do this natively in C#? Right now I'm using a conversion
function that takes an index and returns a cell reference. I'd like to
eliminate the function, if I can. Thanks in advance.


I don't think so. Your best strategy may be to allocate your array as
a 43 element array. That way, the code that needs to deal with rows
and columns can call your product and sum methods, while the code that
can deal with vectors goes straight to the vector.

--
<http://www.midnightbea ch.com>
Jan 19 '06 #3
David Veeneman wrote:
I have a two-dimensional array with 6 x 7 elements. I'd like to be able to
reference the elements sequentially, as if the rows were laid end-to-end. I
know the Array.Length property will give me the length of the array as 42,
but I'd like to be able to reference specific elements. For example, I'd
like to be able to reference foo[3,2] as foo[24].

Is there any way to do this natively in C#? Right now I'm using a conversion
function that takes an index and returns a cell reference. I'd like to
eliminate the function, if I can. Thanks in advance.


Just in case anyone else was investigating this line of enquiry - using
the IList indexer implementation for arrays doesn't work. For instance:

using System;
using System.Collecti ons;

class Test
{
static void Main()
{
string[,] array = new string[10,20];
array[0,5] = "Hello";
array[3,4] = "There";

IList list = (IList)array;

Console.WriteLi ne (list[5]);
Console.WriteLi ne (list[64]);
}
}

compiles but gives the following result:
Unhandled Exception: System.Argument Exception: Array was not a
one-dimensional array.
at System.Array.Ge tValue(Int32 index)
at System.Array.Sy stem.Collection s.IList.get_Ite m(Int32 index)
at Test.Main()

(Using 2.0 and generics doesn't help either as far as I can see.)

Jon

Jan 19 '06 #4
On Wed, 18 Jan 2006 19:28:32 -0600, "David Veeneman"
<da****@nospam. com> wrote:
I have a two-dimensional array with 6 x 7 elements. I'd like to be able to
reference the elements sequentially, as if the rows were laid end-to-end.


That's not directly possible with .NET arrays, at least not in C#.
However, you could access the array with foreach -- the iterator will
loop through all elements sequentially, but you won't know the current
overall index unless you keep track of it yourself.
--
http://www.kynosarges.de
Jan 19 '06 #5
Christoph Nahr wrote:
I have a two-dimensional array with 6 x 7 elements. I'd like to be able to
reference the elements sequentially, as if the rows were laid end-to-end.
That's not directly possible with .NET arrays, at least not in C#.
However, you could access the array with foreach -- the iterator will
loop through all elements sequentially, but you won't know the current
overall index unless you keep track of it yourself.


In fact, it's not just C#. As far as I can tell, IL doesn't have any
direct instructions for accessing an array element unless the array is
actually a vector (in CLI terminology) - a single-dimensional array
with a lower bound of 0.
From the CLI spec (first edition, admittedly), section 4.7 of partition

III:

<quote>
The ldelem instruction loads the value of the element with index
'index' (of type int32 or native int) in the zero-based, one
dimensional array 'array' and places it on the top of the stack.
....
For one-dimesional arrays that aren't zero-based, and for
multi-dimensional arrays, the array class provides a Get method.
</quote>

Of course, it wouldn't be hard to write an ArrayUtil class which took
an arbitrary Array and an index, then use GetUpperBounds etc to access
the relevant element. It wouldn't be very efficient though...

Jon

Jan 19 '06 #6
I was afraid that was the case. For the benefit of anyone else researching
the question, here is the code I use to get a cell reference from an index
number. It assumes a 6 x 7 array:
private CellRef GetCellRefFromI ndex(int index)
{
// Get the row number for the index passed in
int row = index / 7;

// Get the column number for the index passed in
int column = (index % 7) - 1;
if (column == -1) column = 6;

// Set return value
return new CellRef(row, column);
}
The code returns a CellRef, which is a custom struct:
private struct CellRef
{
public int Row;
public int Column;

public CellRef(int row, int column)
{
Row = row;
Column = column;
}
}


Jan 19 '06 #7
David Veeneman wrote:
// Get the column number for the index passed in
int column = (index % 7) - 1;
if (column == -1) column = 6;


Looks like 1 <= index <= 43. Fwiw,

int column = (index - 1) % 7;

should be more efficient than your code, with its conditional
statement.

--
<http://www.midnightbea ch.com>
Jan 19 '06 #8
On Wed, 18 Jan 2006 19:28:32 -0600, "David Veeneman"
<da****@nospam. com> wrote:
I have a two-dimensional array with 6 x 7 elements. I'd like to be able to
reference the elements sequentially, as if the rows were laid end-to-end. I
know the Array.Length property will give me the length of the array as 42,
but I'd like to be able to reference specific elements. For example, I'd
like to be able to reference foo[3,2] as foo[24].

Is there any way to do this natively in C#? Right now I'm using a conversion
function that takes an index and returns a cell reference. I'd like to
eliminate the function, if I can. Thanks in advance.


You could wrap the underlying array in a class and provide two
separate indexers: [] and [,]. For reasons of speed I have used one
dimension rather than two for the underlying array. YMMV.

public class CellRefArray {
private int m_rows;
private int m_cols;
private CellRef[] m_CRArray;

// Constructor
public CellRefArray(in t rows, int cols) {
m_rows = rows;
m_cols = cols;
m_CRArray = new CellRef[m_rows * m_cols];
}

// Indexer[]
public CellRef this[int i] {
get { return m_CRArray[i]; }
set { m_CRArray[i] = value; }
}

// Indexer[,]
public CellRef this[int r, int c] {
get { return m_CRArray[r * m_cols + c]; }
set { m_CRArray[r * m_cols + c] = value; }
}
}

You may want to add some range checking to the two indexers.

Depending on precisely what you want you might also want to add a
second constructor that takes an array[,] as parameter or a property
that returns an array[,].

rossum
--

The ultimate truth is that there is no ultimate truth
Jan 19 '06 #9
Jon Shemitz <jo*@midnightbe ach.com> wrote:
David Veeneman wrote:
// Get the column number for the index passed in
int column = (index % 7) - 1;
if (column == -1) column = 6;


Looks like 1 <= index <= 43. Fwiw,

int column = (index - 1) % 7;

should be more efficient than your code, with its conditional
statement.


However, it's not equivalent. The index 0 would give column=-1 with
your code, but column=6 for David's. To make it equivalent, however
(for non-negative values of "index") you could use (index+6)%7 instead.

Alternatively, it would be worth trying Math.DivRem. I haven't
benchmarked it, so I've no idea whether it would be faster or not - but
if efficiency is critical, it's worth a try.

I'm not sure why David's subtracting one in the first place, however...
I don't think he should be doing so.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Jan 19 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
1674
by: Bosconian | last post by:
I've been researching this for hours and can't seem to find the right syntax. I need to retrieve a value of an array by referencing the element using a string variable. For example: $data = 'hank'; $element = 'lastname';
1
3622
by: JavaDeveloper | last post by:
Is it possible to reference another XSD file within an XSD file? What I'd like to do is have a fairly static XSD file which contains an element whose valid values change often reference a 2nd XSD file which specifies the valid values for that element. This way I could set up a process that reads the valid values for the element from a database and then re-create the 2nd XSD file as needed.
2
8061
by: Simon | last post by:
Am using the following code. <script language="JavaScript1.2"> function setquantity(productindex,productquantity) { //create the reference object irefname_none = eval("document." + productindex + "none"); <snip>
5
1218
by: Tim Johnson | last post by:
Hi: Is it possible to reference a table which contains a select list that has an event handler that modifies the table, without using the table ID? Example: <table id="SearchTable"> event handler in select list is onChange="addTableRow('SearchTable')" And in addTableRow(), I have the following code:
11
2118
by: Edd | last post by:
Hello all, I've made a data structure and an associated set of functions to enable me to store a dynamically-sized array of elements of whatever data type I like. Well that's the idea anyway... My implementation seems to work great for primitive types, structures and unions, but I can't quite get an array of function-pointers working properly. Here's a very reduced version of my code with error checks removed for the sake of brevity.
6
2481
by: Mikey_Doc | last post by:
Hi We are running cms 2002, Framework 1.0 with Visual studio 2002. We have just upgraded to Framework 1.1 and visual studio 2003. All of our database connection strings are stored within the machine config, this was necessary as our web site has 4 environments and the database server has a different name in each. Since the upgrade the applications can't read the strings in the
0
1301
by: Doug Gault | last post by:
I've been very pleased to find that you can load an XML file into a DATASET using the XMLREAD method, but I'm having a problem when trying to load a file that contains self-referencing elements. Here is an excerpt from the .XSD file ... ================================================ XSD SCHEMA DOC ================================================
10
5167
by: rshepard | last post by:
While working with lists of tuples is probably very common, none of my five Python books or a Google search tell me how to refer to specific items in each tuple. I find references to sorting a list of tuples, but not extracting tuples based on their content. In my case, I have a list of 9 tuples. Each tuple has 30 items. The first two items are 3-character strings, the remaining 28 itmes are floats. I want to create a new list from...
2
1630
by: Mystagogue | last post by:
Is it possible for a single xpath expression, perhaps using back- referencing, to return the only the "item" elements having a "result" that matches the parent "foo result"? <foo result="false" > <item id="1" result="true"/> <item id="2" result="false/> </foo> In other words, I want to have the element with id="2"
0
9883
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
11359
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10928
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
11069
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10543
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9734
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
7259
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5944
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
6149
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.