I'm getting the error:
"Ambiguity between 'game.Form1.WallCheckerArray' and
'game.Form1.WallCheckerArray'"
Because I use it twice. Why can't I use the same array name twice with different values? My code is below. The array exists out of cordinates.
my array:
private int[,] WallCheckerArray = new int[28, 4];// <<----- was the problem
int[,] WallCheckerArray = {
{220,250,13,64},//1
{24,58,24,55},//2
{104,206,22,55},//3
{264,370,22,55},//4
{382,450,22,55},//5
{24,92,74,109},//6
{104,136,74,185},//7
{136,206,114,138},//8
{150,326,74,98},//9
{225,255,98,140},//10
{345,365,74,185},//11
{275,355,114,138},//12
{384,445,74,109},//13
{104,136,200,270},//14
{150,330,240,270},//15
{225,255,270,315},//16
{340,370,200,270},//17
{20,85,285,305},//18
{50,85,305,345},//19
{104,214,285,315},//20
{274,368,285,315},//21
{378,445,285,305},//22
{378,415,305,345},//23
{24,195,365,375},//24
{104,154,335,375},//25
{165,339,335,345},//26
{215,245,335,375},//27
{265,445,365,375},//28
{355,365,335,375}//29
};
int i = 0;
for( i = 0; i < 29; i++)
{
if (((x >= WallCheckerArray[i, 0] && x <= WallCheckerArray[i, 1]) && (y >= WallCheckerArray[i, 2] && y <= WallCheckerArray[i, 3])))//-----------------------------------}-
{
InsideWC();
System.Console.WriteLine(WallCheckerArray[i, 1]);
}
}
A line of code like int[,] WallCheckerArray = something is read by the compiler as "Make a new int[,] named WallCheckerArray. And the problem is, you do that twice in a row; you can't have two different variables with the same name. If you don't give a variable an access modifier, the C# compiler will assume you wanted it to be Private.
To make your code work:
private int[,] WallCheckerArray = new int[28, 4];
WallCheckerArray = {
/* Your Data */
};
FYI: you can actually make your array and fill it with data in the same statement, like so:
private int[,] WallCheckerArray = {
{220,250,13,64},
{24,58,24,55},
{104,206,22,55},
// and so on
};
This way, you don't have to worry about declaring the size of the array, it'll be handled for you.
Had to delete "private int[,] WallCheckerArray = new int[28, 4];"
Related
I want to create array 10 * 10 * 10 in C# like int[][][] (not int[,,]).
I can write code:
int[][][] count = new int[10][][];
for (int i = 0; i < 10; i++)
{
count[i] = new int[10][];
for (int j = 0; j < 10; j++)
count[i][j] = new int[10];
}
but I am looking for a more beautiful way for it. May be something like that:
int[][][] count = new int[10][10][10];
int[][][] my3DArray = CreateJaggedArray<int[][][]>(1, 2, 3);
using
static T CreateJaggedArray<T>(params int[] lengths)
{
return (T)InitializeJaggedArray(typeof(T).GetElementType(), 0, lengths);
}
static object InitializeJaggedArray(Type type, int index, int[] lengths)
{
Array array = Array.CreateInstance(type, lengths[index]);
Type elementType = type.GetElementType();
if (elementType != null)
{
for (int i = 0; i < lengths[index]; i++)
{
array.SetValue(
InitializeJaggedArray(elementType, index + 1, lengths), i);
}
}
return array;
}
You could try this:
int[][][] data =
{
new[]
{
new[] {1,2,3}
},
new[]
{
new[] {1,2,3}
}
};
Or with no explicit values:
int[][][] data =
{
new[]
{
Enumerable.Range(1, 100).ToArray()
},
new[]
{
Enumerable.Range(2, 100).ToArray()
}
};
There is no built in way to create an array and create all elements in it, so it's not going to be even close to how simple you would want it to be. It's going to be as much work as it really is.
You can make a method for creating an array and all objects in it:
public static T[] CreateArray<T>(int cnt, Func<T> itemCreator) {
T[] result = new T[cnt];
for (int i = 0; i < result.Length; i++) {
result[i] = itemCreator();
}
return result;
}
Then you can use that to create a three level jagged array:
int[][][] count = CreateArray<int[][]>(10, () => CreateArray<int[]>(10, () => new int[10]));
With a little help from Linq
int[][][] count = new int[10].Select(x => new int[10].Select(x => new int[10]).ToArray()).ToArray();
It sure isn't pretty and probably not fast but it's a one-liner.
There is no 'more elegant' way than writing the 2 for-loops. That is why they are called 'jagged', the sizes of each sub-array can vary.
But that leaves the question: why not use the [,,] version?
int[][][] count = Array.ConvertAll(new bool[10], x =>
Array.ConvertAll(new bool[10], y => new int[10]));
A three dimensional array sounds like a good case for creating your own Class. Being object oriented can be beautiful.
You could use a dataset with identical datatables. That could behave like a 3D object (xyz = row, column, table)... But you're going to end up with something big no matter what you do; you still have to account for 1000 items.
Why don't you try this?
int[,,] count = new int[10, 10, 10]; // Multi-dimentional array.
Any problem you see with this kind of representation??
In Microsoft Visual Studio (Community Edition of course) I have a simple C# program where I declare a simple array without a set size like so
int[] paths;
In a later part of the program I try to set parts of the array but it gives me an error
Use of unsigned local variable 'paths'
in this part of the program
for (int b = 0; b < 100; b++) {
paths[b] = b;
}
In conclusion, I suppose I'm wondering whether this problem that affects just me, or a problem of syntax. (I originated from Java which is half to blame how I ran into this question) I am willing to accept closure on whether this is possible or not,(If so source please) or If I'm just doing it wrong.(If so please provide a solution/suggestions in comments)
In C# Arrays are fixed size, and need to be initialized
var size = 100;
int[] paths = new int[size];
for (var b = 0; b < size; b++) {
paths[b] = b;
}
List is also another good thing for a C# beginner to know about, the difference between an array and a list, is that a List will resize itself for you automagically (I believe there is a very similar List class in Java)
var size = 100;
var paths = new List<int>();
for (var b = 0; b < size; b++) {
paths.Add(b);
}
You just declared the array, but you also need to create it before using it:
paths = new int[100];
You must follow the array declaration syntax.
int[] paths; //-> here you are declaring the paths array and your not creating array.
in memory it set paths array without its sizes. So you must set the size by creating this array as follows.
int[] paths = new int[10];
you can create and declare array like as follows, for to assign another array with it.
EG:
int[] arr1 = new int[] { 0,1,2,3,4,5,6,7};
int[] paths =arr1;
here arr1 size and data will be automatically assigned to paths array.
Firstly you are creating a variable but you have not assigned it at all, this is the reason for you error.
Secondly in C# arrays require a fixed size and can not be resized so when initializing a size must be provided, either explicitly as below or implicitly by initializing it with objects (see comments).
int[] paths; // declaration
paths = new int[100] // assignment, array initialized with a size of 100
// with objects
// paths = new int[] { 1, 2, 3 };
// declaration and assignment can also be merged into 1 line.
// i.e int[] paths = new int[100]
for (int b = 0; b < 100; b++) {
paths[b] = b;
}
you must declare and initialize the array element in your code like
int[] myInt = new int[100]
If you don't know the size before initialize you need to use List like
List<int> list = new List<int>();
list.Add(123);
list.Add(456);
list.Add(789);
Console.WriteLine(list[2]);
and it is necessary to use array and size of array is not fixed before initialize you need to follow below code but below code is wastage of memory usage and more execution process. so my recommend is use List instead of int[]
// Global Variable
int[] myInt;
int mySize = 1;
private void button1_Click(object sender, EventArgs e)
{
if (mySize > 1)
{
int[] tempInt = new int[mySize];
tempInt = myInt;
myInt = new int[mySize];
for (int i = 0; i < mySize - 1; i++)
{
myInt[i] = tempInt[i];
}
myInt[mySize - 1] = mySize;
}
else
{
myInt = new int[mySize];
myInt[mySize - 1] = mySize;
}
mySize++;
}
I have a two-dimensions array of a fixed size of 50 elements. I need to ask the user for some values and insert them into the array. The problem is "How do I make sure I'm not overwriting anything that's in there?"
There will already be some content in the array when I start the program, but I don't know how much. How can I find the next available ID in the array, to insert my content there without overwriting anything that could be already in there?
I tried using array.GetUpperBound and array.GetLength, however they return fixed values no matter how many elements are already in the array.
I have to use an array, I can't use lists or anything like that.
What can I do to find out the next "free" position in my array?
Thank you very much for helping.
Well if you are using Array, all your values will contain a default value.For example if you have an two-dimensional int array like this:
var arr = new int[2, 3];
arr[1,2] will be equal to 0 which is default value for int.Anyway you can define an extension method to find available position for a two-dimensional array like this:
public static class MyExtensions
{
public static void FindAvailablePosition<T>(this T[,] source, out int x, out int y)
{
for (int i = 0; i < source.GetLength(0); i++)
{
for (int j = 0; j < source.GetLength(1); j++)
{
if (source[i, j].Equals(default(T)))
{
x = i;
y = j;
return;
}
}
}
x = -1;
y = -1;
}
}
And you can use it like this:
var arr = new int[2, 3];
arr[0, 0] = 12; // for example
int x, y;
arr.FindAvailablePosition(out x,out y);
// now x = 0, y = 1
Suppose you have an array like:
double[,] rectArray = new double[10,3];
Now you want the fouth row as a double[] array of 3 elements without doing:
double[] fourthRow = new double[]{rectArray[3,0],
rectArray[3,1],
rectArray[3,2]};
Is it possible someway? Even using a Marshal.Something approach?
Thanks!
You can use Buffer.BlockCopy method:
const int d1 = 10;
const int d2 = 3;
const int doubleSize = 8;
double[,] rectArray = new double[d1, d2];
double[] target = new double[d2];
int rowToGet = 3;
Buffer.BlockCopy(rectArray, doubleSize * d2 * rowToGet, target, 0, doubleSize * d2);
LINQ to the rescue:
var s = rectArray.Cast<double>().Skip(9).Take(3).ToArray();
Explanation: Casting a multi-dimensional array flattens it to a single-dimensional array. After that all we need to do is skip to the element we want (the 4th element in the 2-D array resolves to Skip(9)...) and take 3 elements from it).
Why not make a generic extension method?
public static T[] GetRow<T>(this T[,] input2DArray, int row) where T : IComparable
{
var width = input2DArray.GetLength(0);
var height = input2DArray.GetLength(1);
if (row >= height)
throw new IndexOutOfRangeException("Row Index Out of Range");
// Ensures the row requested is within the range of the 2-d array
var returnRow = new T[width];
for(var i = 0; i < width; i++)
returnRow[i] = input2DArray[i, row];
return returnRow;
}
Like this all you have to code is:
array2D = new double[,];
// ... fill array here
var row = array2D.GetRow(4) // Implies getting 5th row of the 2-D Array
This is useful if you're trying to chain methods after obtaining a row and could be helpful with LINQ commands as well.
You probably want to use a jagged array. That is not an array of 10 by 3 but instead an array of arrays.
Something like :
double[][] rectArray;
....
double [] rowArray = rectArray[3];
There are lots of places to learn more about jagged arrays. For example Dynamically created jagged rectangular array
If you must use a rectangular array and just want to simplify the syntax, you can use a method to get the row like so:
double[] fourthRow = GetRow(rectArray, 3);
public static T[] GetRow<T>(T[,] matrix, int row)
{
var columns = matrix.GetLength(1);
var array = new T[columns];
for (int i = 0; i < columns; ++i)
array[i] = matrix[row, i];
return array;
}
Although this is an old thread, an addition to Joseph Sturtevants answer may be useful. His function crashes in case the matrix's first column is not zero, but another integer.
This is e.g. always the case in case of retrieving data from Excel, like
object[,] objects = null;
Excel.Range range = worksheet.get_Range("A1", "C5");
objects = range.Cells.Value; //columns start at 1, not at 0
The GetRow function could be modified like this:
public static T[] GetRow<T>(T[,] matrix, int row, int firstColumn)
{
var columns = matrix.GetLength(1);
var array = new T[columns];
for (int i = firstColumn; i < firstColumn + columns; ++i)
array[i-firstColumn] = matrix[row, i];
return array;
}
I have an array in c# that is 1-based (generated from a call to get_Value for an Excel Range
I get a 2D array for example
object[,] ExcelData = (object[,]) MySheet.UsedRange.get_Value(Excel.XlRangeValueDataType.xlRangeValueDefault);
this appears as an array for example ExcelData[1..20,1..5]
is there any way to tell the compiler to rebase this so that I do not need to add 1 to loop counters the whole time?
List<string> RowHeadings = new List<string>();
string [,] Results = new string[MaxRows, 1]
for (int Row = 0; Row < MaxRows; Row++) {
if (ExcelData[Row+1, 1] != null)
RowHeadings.Add(ExcelData[Row+1, 1]);
...
...
Results[Row, 0] = ExcelData[Row+1, 1];
& other stuff in here that requires a 0-based Row
}
It makes things less readable since when creating an array for writing the array will be zero based.
Why not just change your index?
List<string> RowHeadings = new List<string>();
for (int Row = 1; Row <= MaxRows; Row++) {
if (ExcelData[Row, 1] != null)
RowHeadings.Add(ExcelData[Row, 1]);
}
Edit: Here is an extension method that would create a new, zero-based array from your original one (basically it just creates a new array that is one element smaller and copies to that new array all elements but the first element that you are currently skipping anyhow):
public static T[] ToZeroBasedArray<T>(this T[] array)
{
int len = array.Length - 1;
T[] newArray = new T[len];
Array.Copy(array, 1, newArray, 0, len);
return newArray;
}
That being said you need to consider if the penalty (however slight) of creating a new array is worth improving the readability of the code. I am not making a judgment (it very well may be worth it) I am just making sure you don't run with this code if it will hurt the performance of your application.
Create a wrapper for the ExcelData array with a this[,] indexer and do rebasing logic there. Something like:
class ExcelDataWrapper
{
private object[,] _excelData;
public ExcelDataWrapper(object[,] excelData)
{
_excelData = excelData;
}
public object this[int x, int y]
{
return _excelData[x+1, y+1];
}
}
Since you need Row to remain as-is (based on your comments), you could just introduce another loop variable:
List<string> RowHeadings = new List<string>();
string [,] Results = new string[MaxRows, 1]
for (int Row = 0, SrcRow = 1; SrcRow <= MaxRows; Row++, SrcRow++) {
if (ExcelData[SrcRow, 1] != null)
RowHeadings.Add(ExcelData[SrcRow, 1]);
...
...
Results[Row, 0] = ExcelData[SrcRow, 1];
}
Why not use:
for (int Row = 1; Row <= MaxRows; Row++) {
Or is there something I'm missing?
EDIT: as it turns out that something is missing, I would use another counter (starting at 0) for that purpose, and use a 1 based Row index for the array. It's not good practice to use the index for another use than the index in the target array.
Is changing the loop counter too hard for you?
for (int Row = 1; Row <= MaxRows; Row++)
If the counter's range is right, you don't have to add 1 to anything inside the loop so you don't lose readability. Keep it simple.
I agree that working with base-1 arrays from .NET can be a hassle. It is also potentially error-prone, as you have to mentally make a shift each time you use it, as well as correctly remember which situations will be base 1 and which will be base 0.
The most performant approach is to simply make these mental shifts and index appropriately, using base-1 or base-0 as required.
I personally prefer to convert the two dimensional base-1 arrays to two dimensional base-0 arrays. This, unfortunately, requires the performance hit of copying over the array to a new array, as there is no way to re-base an array in place.
Here's an extension method that can do this for the 2D arrays returned by Excel:
public static TResult[,] CloneBase0<TSource, TResult>(
this TSource[,] sourceArray)
{
If (sourceArray == null)
{
throw new ArgumentNullException(
"The 'sourceArray' is null, which is invalid.");
}
int numRows = sourceArray.GetLength(0);
int numColumns = sourceArray.GetLength(1);
TResult[,] resultArray = new TResult[numRows, numColumns];
int lb1 = sourceArray.GetLowerBound(0);
int lb2 = sourceArray.GetLowerBound(1);
for (int r = 0; r < numRows; r++)
{
for (int c = 0; c < numColumns; c++)
{
resultArray[r, c] = sourceArray[lb1 + r, lb2 + c];
}
}
return resultArray;
}
And then you can use it like this:
object[,] array2DBase1 = (object[,]) MySheet.UsedRange.get_Value(Type.Missing);
object[,] array2DBase0 = array2DBase1.CloneBase0();
for (int row = 0; row < array2DBase0.GetLength(0); row++)
{
for (int column = 0; column < array2DBase0.GetLength(1); column++)
{
// Your code goes here...
}
}
For massively sized arrays, you might not want to do this, but I find that, in general, it really cleans up your code (and mind-set) to make this conversion, and then always work in base-0.
Hope this helps...
Mike
For 1 based arrays and Excel range operations as well as UDF (SharePoint) functions I use this utility function
public static object[,] ToObjectArray(this Object Range)
{
Type type = Range.GetType();
if (type.IsArray && type.Name == "Object[,]")
{
var sourceArray = Range as Object[,];
int lb1 = sourceArray.GetLowerBound(0);
int lb2 = sourceArray.GetLowerBound(1);
if (lb1 == 0 && lb2 == 0)
{
return sourceArray;
}
else
{
int numRows = sourceArray.GetLength(0);
int numColumns = sourceArray.GetLength(1);
var resultArray = new Object[numRows, numColumns];
for (int r = 0; r < numRows; r++)
{
for (int c = 0; c < numColumns; c++)
{
resultArray[r, c] = sourceArray[lb1 + r, lb2 + c];
}
}
return resultArray;
}
}
else if (type.IsCOMObject)
{
// Get the Value2 property from the object.
Object value = type.InvokeMember("Value2",
System.Reflection.BindingFlags.Instance |
System.Reflection.BindingFlags.Public |
System.Reflection.BindingFlags.GetProperty,
null,
Range,
null);
if (value == null)
value = string.Empty;
if (value is string)
return new object[,] { { value } };
else if (value is double)
return new object[,] { { value } };
else
{
object[,] range = (object[,])value;
int rows = range.GetLength(0);
int columns = range.GetLength(1);
object[,] param = new object[rows, columns];
Array.Copy(range, param, rows * columns);
return param;
}
}
else
throw new ArgumentException("Not A Excel Range Com Object");
}
Usage
public object[,] RemoveZeros(object range)
{
return this.RemoveZeros(range.ToObjectArray());
}
[ComVisible(false)]
[UdfMethod(IsVolatile = false)]
public object[,] RemoveZeros(Object[,] range)
{...}
The first function is com visible and will accept an excel range or a chained call from another function (the chained call will return a 1 based object array), the second call is UDF enabled for Excel Services in SharePoint. All of the logic is in the second function. In this example we are just reformatting a range to replace zero with string.empty.
You could use a 3rd party Excel compatible component such as SpreadsheetGear for .NET which has .NET friendly APIs - including 0 based indexing for APIs such as IRange[int rowIndex, int colIndex].
Such components will also be much faster than the Excel API in almost all cases.
Disclaimer: I own SpreadsheetGear LLC