I have list called “images” which is contained of the series of bitmap images.
My question is how can I loop through every single element of my “images” list and do this operation for different elements of my list “images”?
You want to keep collections for each element of images, right?
You'll need to maintain a list of lists, or something similar:
List<List<int>> stuffOfImages = new List<List<int>>();
for (int x = 0; x < images[i].Width; x++) {
var stuffOfImage = new List<int>();
stuffOfImages.Add(stuffOfImage);
for (int y = 0; y < images[i].Height; y++) {
}
}
Note that you lose all reference to the associated image - it might be worthy creating a type so you can keep a reference to the image and the integer collection associated with it in one place and related.
I'm a little unclear as to what you mean, so please elaborate if necessary.
Related
Im developing a small app/game in Unity3D.
The problem is:
I need to clone an array (call it tempArray) and make some modifications to it. Then i need to change values of the MAIN array to modified tempArray. However, whenever i make changes to cloned array, the same changes are made to the main one.
So i used the following code:
private Cell[,] allCells = new Cell[256, 256];
private Cell[,] cellClone = new Cell[256,256];
//meanwhile initiated to some values//
//Here i clone the array.
cellClone = (Cell[,])allCells.Clone();
//Here i output the values for an element from both arrays.
Debug.Log(cellClone[0, 0].region.name.ToString());
Debug.Log(allCells[0, 0].region.name.ToString());
//Here i want to change "Region" variable of cellClone ONLY.
cellClone[0, 0].setRegion(new Region("testregion123", Color.cyan, false));
//Finally, i output the same values again. Only cellClone should change.
Debug.Log(cellClone[0, 0].region.name.ToString());
Debug.Log(allCells[0, 0].region.name.ToString());
However, the output shows that allCells[0,0] element was also changed. This means that any operation I do to the cloned array, is executed to the main array.
EDIT:
After alot of playing around I implemented this as a solution. Im posting this in case anybody has a similar problem.
But Im not sure if this is how its supposed to be done so if anybody has any information - Ill be checking this post.
for (int i = 0; i < allCells.GetLength(0); i++)
{
for (int j = 0; j < allCells.GetLength(1); j++)
{
//cellClone[i, j] = allCells[i, j].Clone();
//cellClone[i, j] = new Cell((int)allCells[i, j].position.x, (int)allCells[i, j].position.y, allCells[i, j].getRegionName());
cellClone[i, j] = allCells[i, j].clone();
}
}
And the clone function:
public Cell clone()
{
Cell n = new Cell((int)position.x, (int)position.y, regionName);
return n;
}
However, the output shows that allCells[0,0] element was also changed. This means that any operation I do to the cloned array, is executed to the main array.
Unless Cell is a struct, your setRegion method (which sounds like it should really just be a Region property) isn't changing the contents of the array at all. It's changing the data stored in the object that both arrays contain a reference to.
You're performing a shallow clone of the array, which means the references are being copied - but each Cell object is not being cloned. (We don't even know whether that operation has been implemented within Cell.)
It sounds like you want to perform a deep clone, something like:
for (int i = 0; i < allCells.GetLength(0); i++)
{
for (int j = 0; j < allCells.GetLength(1); j++)
{
cellClone[i, j] = allCells[i, j].Clone();
}
}
... where you'd need to implement the Clone method yourself. (It may need to clone the region in turn, for example.)
Check this out:
Array.Copy
Array.Copy (Array, Array, Int32)
Easier and only 1 line of code;
I have array defined like this :
List<DocumentFields>[,] dummyArray = new List<DocumentFields>[8,8];
It takes records from the database. I need to prepare this array for showing in a asp.net mvc3 view so i iterate it the standard way :
for (int i = 0; i < ViewBag.Header.GetLength(0); i++)
{
for (int j = 0; j < ViewBag.Header.GetLength(1); j++)
{
But I realized that in fact for the second iteration I don't need the Length but the count of the elements that are actually there. So instead of ViewBag.Header.GetLength(1) I need this:
ViewBag.Header.Get_Count_Of_The_Elements_For_The_Second_Index
I couldn't find a property that do this right away. Maybe some way of using Length or something... Dunno...
Your dummyArray is a two-dimensional array of lists. To get list size you can use dummyArray[i,j].Count in your inner loop.
Ok so I am making a sudoku solver for fun (yes I know it's already been made many times over) so to let people input there values before solving I used numericalupdown (81 one of them to be exact)
and i wanted to assign all of them to an array:
int[,] Sudoku = new int[9, 9];
and then on clicking "solve" the first thing it's supposed to do is put all the values in the array:
private void button1_Click(object sender, EventArgs e)
{
for (int x = 0; x < 81; x++)
{
for (int y = 0; y < 9; y++)
{
if (x-1 == 0)
{
Sudoku[x - 1, y - 1] = Convert.ToInt32(numericUpDown[y].Value);
}
else
{
Sudoku[x - 1, y - 1] = Convert.ToInt32(numericUpDown[x][y].Value);
}
}
}
}
obviously you can't do: "numbericupdown[y]" but thats for you to see what I am trying to do....
sooooo thoughts?
THANKS,
Craiggles
If you put your numericUpDown controls into a 9x9 grid just like you have for the results, then copying the values will be straightforward.
private void button1_Click(object sender, EventArgs e)
{
for (int x = 0; x < 9; x++)
{
for (int y = 0; y < 9; y++)
{
Sudoku[x, y] = Convert.ToInt32(numericUpDown[x, y].Value);
}
}
}
If the controls are actually all dropped onto the form, then don't do that, remove them from the form. Use code to create them, place them programmatically, and put them into a 2d array. Since this is a learning program anyways, that's good practice for doing GUI's programmatically instead of just by drag-n-drop.
I would go about constructing/placing them dynamically and at the same time putting them into an array or list, but if they are already laid out onto a form you can just add them to a generic list to iterate over them.
List<NumericUpDown> nums = new List<NumericUpDown>();
nums.add(numericUpDwown1);
then you could calculate nums[1]*nums[9]... or whatever
I think I understand what you are doing... Two suggestions: 1) put all of your controls into an array of NumericaUpDown objects. Then you could do numericUpDown[y].Value. Otherwise, 2) name the controls ending with numbers (or some similar convention) then use reflection to find the right one and get its value.
Actually there is no reason at all why you cannot create controls and store them in various collection classes - not just arrays.
I would consider putting these into some sort of structured set of collections that reflect the structure of a sudoku grid.
You could dynamically create and place the controls on the form as well as holding them in the collection.
Basically I have x amount of matrices I need to establish of y by y size. I was hoping to name the matrices: matrixnumber1 matrixnumber2..matrixnumbern
I cannot use an array as its matrices I have to form.
Is it possible to use a string to name a string (or a matrix in this case)?
Thank you in advance for any help on this!
for (int i = 1; i <= numberofmatricesrequired; i++)
{
string number = Convert.ToString(i);
Matrix (matrixnumber+number) = new Matrix(matrixsize, matrixsize);
}
You can achieve a similar effect by creating an array of Matrices and storing each Matrix in there.
For example:
Matrix[] matrices = new Matrix[numberofmatricesrequired];
for (int i = 0; i < numberofmatricesrequired; i++)
{
matrices[i] = new Matrix(matrixsize, matrixsize);
}
This will store a bunch of uniques matrices in the array.
If you really want to you could create a Dictionary<String, Matrix> to hold the matrices you create. The string is the name - created however you like.
You can then retrieve the matrix by using dict["matrix1"] (or whatever you've called it).
However an array if you have a predetermined number would be far simpler and you can refer to which ever you want via it's index:
Matrix theOne = matrix[index];
If you have a variable number a List<Matrix> would be simpler and if you always added to the end you could still refer to individual ones by its index.
I'm curious why you cannot use an array or a List, as it seems like either of those are exactly what you need.
Matrix[] matrices = new Matrix[numberofmatricesrequired];
for (int i = 0; i < matrices.Length; i++)
{
matrices[i] = new Matrix(matrixsize, matrixsize);
}
If you really want to use a string, then you could use a Dictionary<string, Matrix>, but given your naming scheme it seems like an index-based mechanism (ie. array or List) is better suited. Nonetheless, in the spirit of being comprehensive...
Dictionary<string, Matrix> matrices = new Dictionary<string, Matrix>();
for (int i = 1; i <= numberofmatricesrequired; i++)
{
matrices.Add("Matrix" + i.ToString(), new Matrix(matrixsize, matrixsize));
}
I'm trying to write a model containing digital organisms. Within the model i'd liek the environment to be a fixed 2-d array, but each cell needs to contain a list of the organisms in it. I tried using a jagged array, but as the number of occupied elements varies quite a bit throughout the programm run, i need to use something more flexible than an array. I've tried making a 2-D array of the type list, but im getting errors with it.
List<Creature>[,] theWorld;
public Environment()
{
List<Creature>[,] theWorld = new List<Creature>[100,100];
}
public void addCreature(Creature c)
{
for (int x = 0; x < 100; x++)
{
for (int y = 0; y < 100; y++)
{
theWorld[x, y].Add (c);
} } }
this is the segment where i'm trying to declare the array at the beginning, as a type that holds lists (of the organisms), and later i try to add a creature (c) to each of the lists in each element of the array.
when i run it i get the following error message-
"An unhandled exception of type 'System.NullReferenceException' occurred in HGT_sim_2.exe
Additional information: Object reference not set to an instance of an object."
and the line "World[x, y].Add (c);" is highlighted.
If anyone can tell me what i'm doing wrong, and even better, a way around the problem, it'd be amazing.
thank you ain advance!
All your array contains initially is a lot of nulls. You need to actually create the lists...
for(int x = 0 ; x < 100 ; x++)
for(int y = 0 ; y < 100 ; y++)
theWorld[x,y] = new List<Creature>();
Personally, though, I expect this will be a costly way to do things...
It depends in part on whether the data is "sparse" - i.e. are most of the cells usually taken? A simple (but possibly more efficient) approach, for example, would be to use something like multi-map; i.e.
Point pt = new Point(x,y);
theWorld.Add(pt, someCreature);
where theWorld could be something like EditableLookup<Point, Creature> (using EditableLookup<,> from "MiscUtil"). That way, you can still query it by co-ordinate, and have multiple creatures on a coordinate, but you don't have to allocate space for every cell. And because it functions as a dictionary it is still fast. Not as fast as a flat array, but it will scale to bigger (sparse) grids... of course, if the grid has creatures on every cell it could be more expensive! Hence the need to understand your data.
You need to initialize each member of your array, e.g.
for (int x = 0; x < 100; x++)
{
for (int y = 0; y < 100; y++)
{
theWorld[x, y] = new List<Creature>();
} }
Here's the fix:
List<Creature>[,] theWorld;
public Environment()
{
theWorld = new List<Creature>[100,100]; // Remove the type, you were creating a new list and throwing it away...
for(int x = 0 ; x < 100 ; x++)
for(int y = 0 ; y < 100 ; y++)
theWorld[x,y] = new List<Creature>();
}
public void addCreature(Creature c)
{
for (int x = 0; x < 100; x++)
{
for (int y = 0; y < 100; y++)
{
theWorld[x, y].Add (c);
} } }
When you do this:
List<Creature>[,] theWorld = new List<Creature>[100,100];
You're creating an array of List<Creature> references, but they are all empty (pointing to null, not a valid List). You need to initialize each individual element:
for (int x = 0; x < 100; x++) {
for (int y = 0; y < 100; y++) {
theWorld[i,j] = new List<Creature>();
}
}
Once you've done that, you'll be able to call .Add on the individual members.
You're doing it almost correct. Your variable is a 2D array of List<Creature>. Now, List<Creature> is a reference type, so the array is initialized to contain null's in all its members. Thus you get the NullReferenceException. The line
theWorld[x, y].Add (c);
is basically equivalent to
null.Add (c);
All you need to do is to initialize all the members to contain instances of List<Creature>. The best way to do this would be in the constructor. Just rewrite it like this:
public Environment()
{
theWorld = new List<Creature>[100,100];
for(int x = 0 ; x < 100 ; x++)
for(int y = 0 ; y < 100 ; y++)
theWorld[x,y] = new List<Creature>();
}
Now all the operations will work as expected.
Also note, that in your example you are creating a local variable with the same name as the class member. This way you don't initialize the class member at all - it stays null.
You have created the array object to hold your lists, but you haven't created the list itself. You will need to do the following in your constructor:
for (int x = 0; x < 100; x++)
for (int y = 0; y < 100; y++)
theWorld[x,y] = new List<Creature>();
Another problem: you were also defining theWorld as a local variable in your constructor, which means your theWorld field on Environment was never initialized, either.
However, 10,000 Lists may be overkill for what you really need. If your Environment really needs a Creature at every point, and some Creatures may move to other points (where there is more than one at a point, then it may make more sense to use a Dictionary<Point, IList<Creature>> as your model versus 10,000 lists.
public void Add(Creature c, Point at)
{
IList<Creature> list;
if (!theWorld.TryGetValue(at)) {
list = theWorld[at] = new List<Creature>();
}
list.Add(c);
}
You can then implement Move and Remove methods similarly. Also, note that you are adding the same Creature to every point, which (may) mean that there's one Creature at all points in your Environment. You will probably want to create a new Creature() for every point, if that's what you are actually modeling.