C# Array Don't Work at for loop - c#

My Code:
DataTable dt = fs.DataTable;
int columnsNumber = dt.Columns.Count;
string[] array = new string[columnsNumber];
for (int k=0; k==columnsNumber; k++)
{
array[k] = dt.Columns[k].ColumnName;
}
foreach (var item in array)
{
MessageBox.Show(item);
}
MessageBox has displaying the blank message.
If I have run this code, no problem;
array[1] = dt.Columns[1].ColumnName;
array[2] = dt.Columns[2].ColumnName;
array[3] = dt.Columns[3].ColumnName;
This work. What is the problem ?

You have included a == operator in for loop where you should be using <
Change
for (int k=0; k==kolonSayisi; k++)
to
for (int k=0; k<kolonSayisi; k++)

Your cicle just checking k==kolonSayisi:
for (int k=0; k==kolonSayisi; k++)
{
array[k] = dt.Columns[k].ColumnName;
}
I think you should write it like this:
for (int k=0; k < columnsNumber; k++)
{
array[k] = dt.Columns[k].ColumnName;
}

You can also use this way
var listToArray = new listToArray<string>();
foreach (DataColumn dataCol in dt.Columns)
listToArray.Add(dataCol.ColumnName);
listToArray.ToArray();
Hope it helps.

A for loop works the following way:
In the parentheses the first part defines a counting or increment variable and sets the starting value. The second part is the cancel condition. You can read it like: if condition is false then stop the loop. The third part defines the step size, how you want to increment your variable.
Now if you look at your condition k==columnsNumber you are trying to check if k equals the number. In the first iteration where k is 0 it will return false if columnsNumber is not 0. So your loop will stop.

You can use like this:
DataTable table = new DataTable();
table.Columns.Add("col1");
table.Columns.Add("col2");
table.Columns.Add("col3");
var array = table.Columns
.Cast<DataColumn>()
.Select(c => c.ColumnName)
.ToArray();
foreach(var item in array)
{
MessageBox.Show(item);
}

Related

How to make a Jagged Array?

Thinking like a simple array:
Console.WriteLine("Number: ");
int x = Convert.ToInt32(Console.ReadLine());
string[] strA = new string[x];
strA[0] = "Hello";
strA[1] = "World";
for(int i = 0;i < x;i++)
{
Console.WriteLine(strA[i]);
}
Now, how can I do it with a double array?
I've already tried this:
Console.WriteLine("Number 1: ");
int x = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Number 2: ");
int y = Convert.ToInt32(Console.ReadLine());
// Got an error, right way string[x][];
// But how can I define the second array?
string[][] strA = new string[x][y];
strA[0][0] = "Hello";
strA[0][1] = "World";
strA[1][0] = "Thanks";
strA[1][1] = "Guys";
for(int i = 0;i < x;i++)
{
for(int j = 0;i < y;i++)
{
// How can I see the items?
Console.WriteLine(strA[i][j]);
}
}
If's there's a simpler way of doing this, i'll be happy to learn it.
It's only for knowledge, I'm studying double array for the first time, so have patience please :)
Here's my example:
https://dotnetfiddle.net/PQblXH
You are working with jagged array (i.e. array of array string[][]), not 2D one (which is string[,])
If you want to hardcode:
string[][] strA = new string[][] { // array of array
new string[] {"Hello", "World"}, // 1st line
new string[] {"Thanks", "Guys"}, // 2nd line
};
in case you want to provide x and y:
string[][] strA = Enumerable
.Range(0, y) // y lines
.Select(line => new string[x]) // each line - array of x items
.ToArray();
Finally, if we want to initialize strA without Linq but good all for loop (unlike 2d array, jagged array can contain inner arrays of different lengths):
// strA is array of size "y" os string arrays (i.e. we have "y" lines)
string[][] strA = new string[y][];
// each array within strA
for (int i = 0; i < y; ++i)
strA[i] = new string[x]; // is an array of size "x" (each line of "x" items)
Edit: Let's print out jagged array line after line:
Good old for loops
for (int i = 0; i < strA.Length; ++i) {
Console.WriteLine();
// please, note that each line can have its own length
string[] line = strA[i];
for (int j = 0; j < line.Length; ++j) {
Console.Write(line[j]); // or strA[i][j]
Console.Write(' '); // delimiter, let it be space
}
}
Compact code:
Console.Write(string.Join(Environment.newLine, strA
.Select(line => string.Join(" ", line))));
You're using a jagged array instead of a multidimensional one. Simply use [,] instead of [][]. You can then use it with new string[x, y].
First you need to clarify thing in your head before writing code.
I will recommend writing in simple phrase what you want to do. The code in your fiddle go into every direction. I will address the code in the fiddle and not your questionas you have typo error and other issue that where not present in the fiddle while the fiddle has error that the question do not have.
To simplify the problem lets use clear understandable names. The 2d array will be an table, with rows and columns.
// 1/. Ask for 2table dim sizes.
Console.WriteLine("Enter number of rows:");
var x = int.Parse(Console.ReadLine());
Console.WriteLine("Enter number of columns:");
var y = int.Parse(Console.ReadLine());
var table = new string[x, y];
You need to to declare your table before knowing its size.
// 2/. Fill the board
for (int row = 0; row < table.GetLength(0); row++)
{
for (int col = 0; col < table.GetLength(1); col++)
{
Console.WriteLine($"Enter the value of the cell [{row},{col}]");
table[row, col] = Console.ReadLine();
}
}
table.GetLength(0) is equivalent to X, and table.GetLength(1) is equivalent to Y, and can be replace.
// 3/. Display the Table
Console.Write("\n");
for (int row = 0; row < table.GetLength(0); row++)
{
for (int col = 0; col < table.GetLength(1); col++)
{
Console.Write(table[row, col]);
}
Console.Write("\n");
}
For a 3x3 table with 00X, 0X0, X00 as inputs the result is
00X
0X0
X00
It works. You separate each cell when we display by simply adding a comma or a space.
Fiddle
And for Jagged Array:
// 1/. Ask for 2table dim sizes.
Console.WriteLine("Enter number of rows:");
var x = int.Parse(Console.ReadLine());
var table = new string[x][];
// 2/. Fill the board
for (int row = 0; row < table.GetLength(0); row++)
{
Console.WriteLine($"Enter of the line n°{row}");
var lineSize = int.Parse(Console.ReadLine());
table[row] = new string[lineSize];
for (int col = 0; col < table[row].Length; col++)
{
Console.WriteLine($"Enter the value of the cell [{row},{col}]");
table[row][col] = Console.ReadLine();
}
Console.Write("\n");
}
// 3/. Display the Table
Console.Write("\n");
for (int row = 0; row < table.Length; row++)
{
for (int col = 0; col < table[row].Length; col++)
{
Console.Write(table[row][col]);
}
Console.Write("\n");
}
Wrong variable in use:
for(int j = 0;i < y;i++) <- Should be j
{
// How can I see the items?
Console.WriteLine(strA[i][j]);
}

Values in a Dictionary are getting replaced by last value in C#

I have a Dictionary type variable where I'm keeping "string" type key and "List " type values.
The problem is, in case of loop all the previous values are getting replaced by the last value.
Why this happens?
List<IWebElement> indicationsElement = ReturnIndicationList();
drugsDB = new List<string>();
for (int i = 0; i < indicationsElement.Count;i++ )
{
string key = indicationsElement[i].Text.ToString();
dt = ZittarPatt.getDrugsByIndication(ClientName, key);
drugsDB.Clear();
for (int k = 0; k < dt.Rows.Count; k++)
{
drugsDB.Add(dt.Rows[k].ItemArray[3].ToString().Trim());
}
drugsByindicationDictionary.Add(key, drugsDB);
}
You're adding the same reference every iteration instead of adding new instance of List<string>.
Every time you use .Clear it clears all the entries at drugsByindicationDictionary which are already the same entry.
Thus, only the last addition to drugsDB will be saved. (No .Clear is used at the end)
You should do the following code:
List<IWebElement> indicationsElement = ReturnIndicationList();
for (int i = 0; i < indicationsElement.Count;i++ )
{
string key = indicationsElement[i].Text.ToString();
dt = ZittarPatt.getDrugsByIndication(ClientName, key);
var drugsDB = new List<string>();
for (int k = 0; k < dt.Rows.Count; k++)
{
drugsDB.Add(dt.Rows[k].ItemArray[3].ToString().Trim());
}
drugsByindicationDictionary.Add(key, drugsDB);
}
Change drugsDB.Clear(); to drugsDB = new List<string>();

C# multi-dimension array sort based on user input

How can I sort a 2D array in C#
I have looked at other answers to this question but they don't do exactly what I need.
The array is variable height * 5 across
The array holds strings
I need the array sorted based on either column, for example sort in alphabetical the third column, however all other columns must be updated.
Does anyone know of a quick and easy solution?
My code is a mess, here is a shortened version:
string[,] tmp = new string[2, 3];//this is filled with strings
string y = Console.ReadLine();
int x = Convert.ToInt32(y);
// sort tmp based on x column
How do I sort a two-dimensional array in C#? contains a possible solution to this by reading your data into a datatable and then using the object's methods to sort:
// assumes stringdata[row, col] is your 2D string array
DataTable dt = new DataTable();
// assumes first row contains column names:
for (int col = 0; col < stringdata.GetLength(1); col++)
{
dt.Columns.Add(stringdata[0, col]);
}
// load data from string array to data table:
for (rowindex = 1; rowindex < stringdata.GetLength(0); rowindex++)
{
DataRow row = dt.NewRow();
for (int col = 0; col < stringdata.GetLength(1); col++)
{
row[col] = stringdata[rowindex, col];
}
dt.Rows.Add(row);
}
// sort by third column:
DataRow[] sortedrows = dt.Select("", "3");
// sort by column name, descending:
sortedrows = dt.Select("", "COLUMN3 DESC");
So first we'll want to convert the multi-dimensional array into a sequence of single-dimensional arrays representing the rows, so that each row can be manipulated as a unit:
public static IEnumerable<T[]> GetRows<T>(T[,] array)
{
for (int i = 0; i < array.GetLength(0); i++)
{
T[] row = new T[array.GetLength(1)];
for (int j = 0; j < row.Length; j++)
{
row[j] = array[i, j];
}
yield return row;
}
}
Then we'll also need a method that does the reverse to get a multi-dimensional array back when we're done:
public static T[,] ToMultiDimensionalArray<T>(T[][] rows)
{
T[,] output = new T[rows.Length, rows[0].Length];
for (int i = 0; i < rows.Length; i++)
for (int j = 0; j < rows[0].Length; j++)
{
output[i, j] = rows[i][j];
}
return output;
}
Now we just need to sort a sequence of arrays, and Linq makes this quite easy:
tmp = ToMultiDimensionalArray(GetRows(tmp)
.OrderBy(row => row[2]).ToArray());

Delete row of 2D string array in C#

I am making a program that stores data in a 2D array. I would like to be able to delete rows from this array. I cannot figure out why this code doesn't work:
for (int n = index; n < a.GetUpperBound(1); ++n)
{
for (int i = 0; i < a.GetUpperBound(0); ++i)
{
a[i, n] = a[i, n + 1];
}
}
Could someone please help me out? I would like it to delete a single row and shuffle all the rows below it up one place. Thankyou!
you need to create a new array if you want to delete an item
try something like this
var arrayUpdated = new string[a.GetUpperBound(1)][a.GetUpperBound(0)-1];
for (int n = index; n < a.GetUpperBound(1); n++)
{
for (int i = 0; i < a.GetUpperBound(0); i++)
{
arrayUpdated [i, n] = a[i, 1];
}
}
The nested for loop method here works well: https://stackoverflow.com/a/8000574
Here's a method that converts the outer loop of the [,] array method above to use linq. Using linq here is only recommended if you are also doing other things with linq during the traversal.
public T[,] RemoveRow<T>(T[,] array2d, int rowToRemove)
{
var resultAsList = Enumerable
.Range(0, array2d.GetLength(0)) // select all the rows available
.Where(i => i != rowToRemove) // except for the one we don't want
.Select(i => // select the results as a string[]
{
T[] row = new T[array2d.GetLength(1)];
for (int column = 0; column < array2d.GetLength(1); column++)
{
row[column] = array2d[i, column];
}
return row;
}).ToList();
// convert List<string[]> to string[,].
return CreateRectangularArray(resultAsList); // CreateRectangularArray() can be copied from https://stackoverflow.com/a/9775057
}
used Enumerable.Range to iterate all rows as done in https://stackoverflow.com/a/18673845
Shouldn't ++i be i++? ++i increments before matrix operation is performed(ie pre-increment)

Looping array inside list in C#

I have a list of arrays that contains multiple arrays.
Each array has 2 indexes.
First, I want to loop the list. Then I want to loop the array inside the list.
How can I do that ?
I tried to use this way, but it doesn't work:
1. foreach (string[] s in ArrangList1)
2. {
3. int freq1 = int.Parse(s[1]);
4. foreach (string[] s1 in ArrangList)
5. {
6. int freq2 = int.Parse(s1[1]);
7. if (freq1 < freq2)
8. {
9. backup = s;
10. index1 = ArrangList1.IndexOf(s);
11. index2 = ArrangList.IndexOf(s1);
12. ArrangList[index1] = s1;
13. ArrangList[index2] = s;
14. }
15. backup = null;
16. }
17. }
It give me error in line 4.
I try to do the loop using other way, but I don't know how to continue.
for (int i = 0; i < ArrangList1.Count; i++)
{
for (int j = 0; j < ArrangList1[i].Length; j++)
{
ArrangList1[i][1];
}
}
I use C#.
How can I fix this problem?
The error in line4 might be due to a typo using ArrangList. I think you only have ArrangList1 defined. Regardless, the logic is wrong. If you have a list containing arrays, you want to do a foreach on the list, then a foreach on each list item (which is an array).
It's not clear what your types are, so I'm assuming that ArrangList is a list of string arrays.
foreach(string[] s in ArrangList1)
{
foreach(string innerS in s)
{
//now you have your innerString
Console.WriteLine(innerS);
}
}
In your second example,
You have a typo as well...
for (int i = 0; i < ArrangList1.Count; i++)
{
for (int j = 0; j < ArrangList1[i].Length; j++)
{
ArrangList1[i][1]; //the 1 here should be j
}
}
You can also use LINQ and one foreach loop:
// assuming ArrangList1 is List<string[]>
var query = from a in ArrangList1
from b in a
select b;
foreach (String s in query)
{
System.Console.Writeline(s);
}

Categories