Can't get my array loop right - c#

I'm getting an Index was outside the bounds of the array.
string[] paths = {
"\\\\server\\c$\\folder\\subfolder\\user1\\300\\1\\abc.docx",
"\\\\server\\c$\\folder\\subfolder\\user2\\400\\1\\xyz.docx",
};
FileInfo[] f = new FileInfo[paths.Length];
for (int i = 0; i <= paths.Length; i++)
{
f[i] = new FileInfo(paths[i]);
Console.WriteLine(f[i].Length);
}
I can't seem to figure out why, any ideas?

use < instead of <=
for (int i = 0; i < paths.Length; i++)
{
f[i] = new FileInfo(paths[i]);
Console.WriteLine(f[i].Length);
}

Arrays start counting itens from 0. So, if you have an array with length 2, your objects will be in position [0] and [1]. If you try to access the position [2], you'll get the Index was outside the bounds of the array exception, because index 2 doesn't exist in this array.
In your for loop, you're using <= paths.Length. Your paths length is 2. 2 is less or equals 2, so your code will be executed like this
f[2] = new FileInfo(paths[2]) //Position 2 doesn't exist
To solve this, just change from:
for (int i = 0; i <= paths.Length; i++)
To:
for (int i = 0; i < paths.Length; i++)

You have two items in your array
paths[0], paths[1]
Your looping over three items
paths[0], paths[1], paths[2]
To correct this, change
for (int i = 0; i <= paths.Length; i++)
to
for (int i = 0; i < paths.Length; i++)

Related

Index out of bounds when assigning list item by indexer

Can anyone explain to me why I get error of index out of bounds in the below code ? please notice I can not specify the size of any array and I need it to be dynamic :
List<int[]> rows = new List<int[]>();
List<int> FoundAs = new List<int>();
for (int k = 0; k < 1000; k++)
{
for (int i = 0; i < 10000; i++)
FoundAs.Add(i);
rows[k] = FoundAs.ToArray(); // Here is the error
FoundAs.Clear();
}
UPDATE :
The issue is solved , but still I can't access the inner arrays for instance :
int[] temp = new int[rows[y].Length]; // Index out of Bounds
for (int i=0;i<temp.Length;i++)
{
// Do Something
}
You have to add to the list because it is currently empty.
rows.Add(FoundAs.ToArray());

Do you always have to start at the index zero when writing a 2D list?

I want to fill in a 2Dlist, but start at the third position [2]. Is this somehow possible?
A short code for understanding what i mean:
List<List<string>> List2D = new List<List<string>>();
for (int i = 0; i < 5; i++)
{
List2D[2].Add("i")
}
I get the following error:
Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index
EDIT: Any idea how to fill in a 4D list?
List<List<List<List<string>>>> List4D = new List<List<List<List<string>>>>();
for (int i = 0; i < List1.Count; i++)
{
List<List<List<string>>> List3D = new List<List<List<string>>>();
for (int j = 0; j < List2.Count; j++)
{
List<List<string>> List2D = new List<List<string>>();
for (int k = 0; k < List3.Count; k++)
{
List<string> Lijst1D = new List<string>();
List2D.Add(Lijst1D);
}
List3D.Add(List2D);
}
List4D.Add(List3D);
}
So later I can call: List4D[2][3][0].Add("test");
Since you just created your List2D and not added any nested list into it, you can't access its third element (there is nothing there).
You have to add some items first:
List<List<string>> List2D = new List<List<string>>();
List2D.Add(new List<string>());
List2D.Add(new List<string>());
List2D.Add(new List<string>());
for (int i=0; i<5; i++)
{
List2D[2].Add("i")
}
Update
Well, core idea of filling that list remains the same: if you want to access List4D[2][3][0] - first you need to fill all of lists in "path".
You can do it something like this:
List<List<List<List<string>>>> List4D = new List<List<List<List<string>>>>();
int i1 = 2, i2 = 3, i3 = 0;
for (int i = 0; i <= Math.Max(i1, 1); i++)
List4D.Add(new List<List<List<string>>>());
for (int i = 0; i <= Math.Max(i2, 1); i++)
List4D[i1].Add(new List<List<string>>());
for (int i = 0; i <= Math.Max(i3, 1); i++)
List4D[i1][i2].Add(new List<string>());
List4D[i1][i2][i3].Add("test");
Frankly, idea of 4D list looks a little bit "syntetic". In real application probably it is not the best data structure because of clumsy addressing.

How to get the current length of different arrays in jagged arrays using for-loops in c#

static void Main(string[] args)
{
char[][] array = {new char[] {'2','A','3','E'},
new char[] {'F','A'},
new char[] {'F','F','F','F'},
new char[] {'5','A','0','E','9'}};
List<double> arr = new List<double>();
List<double> results = new List<double>();
for (int i = 0; i < array.Length; i++)
{
double result = 0;
for (int index = 0; index < **array.Length**; index++)
{
char c = array[i][index];
if (c > 47 && c < 58)
{
arr.Add(c - 48);
}
else
{
arr.Add((c - 65)+10);
}
}
int power = arr.Count();
for (int ind = 0; ind < power; ind++)
{
arr[ind] = Math.Pow(16, power - 1) * arr[ind];
power--;
result += arr[ind];
}
arr = new List<double>();
results.Add(result);
}
}
My goal is to convert these HEX numeric system numbers to Decimal numeric system numbers.
I know the easy and short way using Console.WriteLine()methods and Standard Numeric Format Strings, but the point is to do this hard way(using jagged arrays). All code work properly , but i dont know how to do change(or get current) value length of different inner arrays in jagged array. If i do it this way usign array.Length - it stay static and doesnt change like i need. I try to use array.GetLength(i) but it dosent work 2.
for (int i = 0; i < array.Length; i++)
...
for (int index = 0; index < **array.Length**; index++)
To get the required length, try
for (int i = 0; i < array.Length; i++)
...
for (int index = 0; index < array[i].Length**; index++)
You are checking the length of the outer array (array.Length), while you meant to read the size of the second, inner array (array[i].Length). Try this:
for (int i = 0; i < array.Length; i++)
{
double result = 0;
for (int index = 0; index < array[i].Length; index++)
I would prefer for each
var array = new[]{new[] {'2','A','3','E'},
new[] {'F','A'},
new[] {'F','F','F','F'},
new[] {'5','A','0','E','9'}};
foreach (var item in array)
{
Console.WriteLine(item.Length);
}

resolution of the following error?

private static void VisualizarAgendaOrdenada()
{
Pacientes.Sort();
for(int i = 0; i <= Pacientes.Count; i++)
{
var agenda = Agendas.Find(p => p.Paciente.Nome == Pacientes[i].Nome);
if (agenda != null)
{
Error,
"Index is out of bounds. Index cannot be negative or greater than the size of the collection."
Your loop condition is wrong: you may not loop until <= Pacientes.Count, but only until < Pacientes.Count.
for (int i = 0; i < Pacientes.Count; i++)
Otherwise you will try to access an index that is outside the range of the list. A list with Count elements is indexed from 0 to Count-1.
You're trying to read from the list under index which does not exist. Change your <= to <.
for(int i = 0; i < Pacientes.Count; i++)
Because arrays/lists are indexed starting from 0 when you need to iterate over all elements you always have to use < Count() or < Length.

Multi-Dimensional Data Structures in C#

How do you create a multi-dimensional data structure in C#?
In my mind it works like so:
List<List<int>> results = new List<List<int>>();
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
{
results[i][j] = 0;
}
}
This doesn't work (it throws an ArgumentOutOfRangeException). Is there a multi-dimensional structure in C# that allows me to access members through their indexes?
The problem here is that List doesn't automatically create elements. To initialise a List<List<T>> you need something like this:
List<List<int>> results = new List<List<int>>();
for (int i = 0; i < 10; i++)
{
results.Add(new List<int>());
for (int j = 0; j < 10; j++)
{
results[i].Add(0);
}
}
Note that setting Capacity is not sufficient, you need to call Add the number of times you need. Alternatively, you can simplify things by using Linq's Enumerable class:
List<List<int>> results = new List<List<int>>();
for (int i = 0; i < 10; i++)
{
results.Add(new List<int>());
results[i].AddRange(Enumerable.Repeat(0, 10));
}
Again, note that Enumerable.Repeat(new List<int>(), 10) will not work, since it will add 10 references to the same list.
Another approach using Linq to the extreme:
List<List<int>> results = Enumerable.Repeat(0, 10)
.Select(i => Enumerable.Repeat(0, 10).ToList())
.ToList();
(The unused parameter i is necessary to ensure that you don't reference the same list ten times as discussed above.)
Finally, to access elements, you can use exactly the notation you used before. Once the elements have been added, they can be read or modified as shown:
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
{
results[i][j] = 2;
int x = results[i][j];
}
}
If you know the dimensions of your structure in advance, and you do not plan to add or remove elements, then a 2D array sounds like your thing:
int[,] n = new int[10, 20];
for (int i = 0; i < 10; ++i) {
for (int j = 0; j < 10; ++j) {
n[i, j] = ...
};
};
You have to create the lists and initialize them with zeros before you can't start indexing into them.
List<List<int>> results = new List<List<int>>();
for (int i = 0; i < 10; i++)
{
results.Add(new List<int>(Enumerable.Repeat(0, 10)));
}
You have to actually 1) create each of the inner lists, and 2) set them to that size.
var Results = Enumerable.Range(0, 10).Select(i => Enumerable.Repeat(0, 10).ToList()).ToList();
I'm a bit of a Linq addict, though.
You could use a datatable and add columns and rows? You would then be able to reference them by name or index.

Categories