{
int numlines = txtbox.Lines.Count();
string[] l = txtbox.Lines;
for (int i = 0; i <= numlines; i++)
{
string lona = l[i].Substring(25, 12);
lstbox.Items.Add(lona);
}
}
Hi, I want to move some elements from a textbox to a listbox using a for loop and a substring method. This is the code i tryed and it causes an exception while running it in a loop.
Since C# collections are zero based, correct for loop uses < Count, not <= Count condintion:
for (int i = 0; i < numlines; i++) // i < numlines, not i <= numlines
{
...
}
Let's simplify the routine and get rid of for loop: we add each line which is long enough (so we'll be able to get a Substring):
foreach (string line in txtbox.Lines) {
if (line.Length >= 25 + 12)
lstbox.Items.Add(line.Substring(25, 12));
}
Related
I want to use the bulk insert concept in C# once count reach 20.if we have 40 numbers no issue. but if we get 39 records got a problem, based on if the condition. how we able to avoid this problem. here below I added a simple program for reference.
var numbers = 39 // not static numbers
int count = 0;
for(int i=0; i<=numbers; i++)
{
count++;
if (count == 20)
{
//Logic
count = 0;
}
}
You can determine whether to batch insert the rest files by comparing the counter with the remaining number of files.
int num = 49;
int count = 0;
for(int i = 1; i <= num; i++)
{
count++;
var n = i / 20;
if(i % 20 == 0 ||count == (num - 20 * ( i / 20)))
{
//Logic
count = 0;
}
}
No need of count variable, you can use modulo operator inside for loop
Like
for(int i = 0; i <= numbers; i++)
{
//i != 0 to avoid bulk process at first
if(i != 0 && i % 20 == 0)
{
//Your bulk operation
}
}
I recommend you to use Console.WriteLine() to print value of i and counter in each iteration so that you will understand bug in your code.
var numbers = 39 // not static numbers
int count = 0;
for(int i=0; i<=numbers; i++)
{
count++;
//Print values to understand flow of program
Console.WriteLine($"For i = {i}, value of count is {count}");
if (count == 20)
{
Console.WriteLine("Time to reset count variable");
//Logic
count = 0;
}
}
You can use Linq .Skip() and .Take(), to do batches
var batchSize = 20;
var batchCount = files.Count() / batchSize;
for (int i = 0; i < batchCount; i++)
{
var bulkFiles = files.Skip(i * batchSize).Take(batchSize);
}
I have a list of names (msfuncionarios), with name, RFID-MAC (6 pairs of hexadecimal digits) and others.
When I read the RFID (output in 6 decimal digits), I need to check the name with that MAC.
I have the folowing code, but I think that breaks for memory fault.
The list has 2666 items.
I'm running the program on a Raspberry PI 2 v.B.
string ConvertUidToName(string uid)
{
int j, h;
int k = 0;
string final="";
string[] separators = { "-" };
for (k=0;k <= msfuncionarios.count;k++)
{
TextBox_produto.Text = k.ToString();
string[] words = msfuncionarios[k].MAC.Split(separators, StringSplitOptions.RemoveEmptyEntries);
i = 0;
h = 0;
for (h = 2; h <= 5; h++)
{
j = Convert.ToInt32(words[h], 16);
final = final + j;
}
j = 0;
if (final == uid )
{
return msfuncionarios[k].Nome.ToString();
}
final = "";
}
return uid.ToString();
}
The problem is in your for condition:
for (k=0; k <= msfuncionarios.count; k++)
You are using the <= operator, so the loop runs 2667 times, even for non-existing item msfuncionarios[2666] which is out of bounds. You can fix it by using < operator.
for (k=0; k < msfuncionarios.count; k++)
Solved!
I found a bugg in the API that writes in the list. The list contains empty MAC's and the convertion breaks.
I want to fill my array with struct in a way that it will look like this
I have this code so far :
`for (int i = 1; i <= n; i++)
{
for (int j = 0; j <=(n - i); j++)
//i should fill m[,] here
for (int j = 1; j <= i; j++)
//i should fill m[,] here
for (int k = 1; k < i; k++)
//i should fill m[,] here
}
for (int i = n - 1; i >= 1; i--)
{
for (int j = 0; j < (n - i); j++)
//i should fill m[,] here
for (int j = 1; j <= i; j++)
//i should fill m[,] here
for (int k = 1; k < i; k++)
//i should fill m[,] here
}`
but I 'm a little bit confused with the index .
how can I adopt this code?
As it's unclear wether the array always has the size 5 I'll assume it has the size n with n being odd and n > 0 (The size is the x and the y size, as I assume that your matrix is quadratic). Then there are several ways to reach the goal your trying to reach, I'll try to present you one I thought of.
First of all we have to think about the array - as it's the easiest way, I'll assume it consists of boolean values (even though you said "I want to fill my array with struct", but as I'm not quite sure what you wanted to say with that and wether you really meant a struct, I'll let this up to you, as this shouldn't be the most difficult part):
var matrix = new bool[n,n];
Then we have to evalueate which fields have to be filled. Therefore we must realize a few things:
The filled fields are always central in their line
The first and last line always have one filled item
The following line always has two more/less filled items, so that the offset is one more than in the previous line
The center line has most items and is the turning point in the amount of filled items
As a first step in developing the algorithm, I'd write a function to fill lines of the array with specific amounts of fields:
private static void FillLine(int line, int count, bool[,] matrix)
{
//Firstly we have to evaluate the offset:
var offset = (matrix.GetLength(0) - count) / 2;
//Then we have to fill the line
for (var x = offset; x < offset + count; x++)
matrix[x, line] = true;
}
Now we simply have to fill the lines for the whole array:
public static void FillDiamond(bool[,] matrix)
{
var count = 1;
for (var line = 0; line < matrix.GetLength(1) / 2; line++)
{
FillLine(line, count, matrix);
count += 2;
}
FillLine(matrix.GetLength(1) / 2, count, matrix);
count = 1;
for (var line = matrix.GetLength(1) - 1; line > matrix.GetLength(1) / 2; line--)
{
FillLine(line, count, matrix);
count += 2;
}
}
Now in a console application you could use this like that:
using System;
namespace SO_c
{
internal static class Program
{
private static void Main()
{
while (true)
{
var n = int.Parse(Console.ReadLine());
if (n < 1 || n % 2 == 0)
continue;
var matrix = new bool[n, n];
FillDiamond(matrix);
for (var y = 0; y < matrix.GetLength(1); y++)
{
for (var x = 0; x < matrix.GetLength(0); x++)
Console.Write(matrix[x, y] ? "█" : " ");
Console.WriteLine();
}
}
}
private static void FillLine(int line, int count, bool[,] matrix)
{
//Firstly we have to evaluate the offset:
var offset = (matrix.GetLength(0) - count) / 2;
//Then we have to fill the line
for (var x = offset; x < offset + count; x++)
matrix[x, line] = true;
}
public static void FillDiamond(bool[,] matrix)
{
var count = 1;
for (var line = 0; line < matrix.GetLength(1) / 2; line++)
{
FillLine(line, count, matrix);
count += 2;
}
FillLine(matrix.GetLength(1) / 2, count, matrix);
count = 1;
for (var line = matrix.GetLength(1) - 1; line > matrix.GetLength(1) / 2; line--)
{
FillLine(line, count, matrix);
count += 2;
}
}
}
}
This can result in output like that:
That's it! Now you should get your diamond for every matrix that fits the rules :)
One way to do it is to calculate the center of the grid and fill in each row, from the center column. In each successive row, we increment the number of blocks we fill in on each side of the center column until we get to the center row, and then we decrement the number of blocks we fill in until we get to the end.
To determine how many blocks to put on each side of the center column for any given row, we can use the row index for the calculation.
Working our way from the top down to the center, the row index represents the number of blocks to add. So, for row index 0, we add 0 blocks on either side of the center column, row index 1 we add 1 block on each side, until we get to the center.
After we get to the center, we want to decrement the number of blocks each time, which can be done by subtracting the row index from the total number of rows.
The code says it better, I think:
private static void Main()
{
while (true)
{
// Get grid size from user and keep it between 1 and the window width
var gridSize = GetIntFromUser("Enter the size of the grid: ");
gridSize = Math.Min(Console.WindowWidth - 1, Math.Max(1, gridSize));
var grid = new bool[gridSize, gridSize];
var center = (gridSize - 1) / 2;
// Populate our grid with a diamond pattern
for (int rowIndex = 0; rowIndex < grid.GetLength(0); rowIndex++)
{
// Determine number of blocks to fill based on current row
var fillAmount = (rowIndex <= center)
? rowIndex : grid.GetUpperBound(0) - rowIndex;
for (int colIndex = 0; colIndex <= fillAmount; colIndex++)
{
grid[rowIndex, center - colIndex] = true;
grid[rowIndex, center + colIndex] = true;
}
}
// Display the final grid to the console
for (int row = 0; row < grid.GetLength(0); row++)
{
for (int col = 0; col < grid.GetLength(1); col++)
{
Console.Write(grid[row, col] ? "█" : " ");
}
Console.WriteLine();
}
}
}
Oh, and this is the helper function I used to get an integer from the user. It's pretty helpful to keep around because you don't have to do any validation in your main code:
private static int GetIntFromUser(string prompt)
{
int value;
// Write the prompt text and get input from user
Console.Write(prompt);
string input = Console.ReadLine();
// If input can't be converted to a double, keep trying
while (!int.TryParse(input, out value))
{
Console.Write($"'{input}' is not a valid number. Please try again: ");
input = Console.ReadLine();
}
// Input was successfully converted!
return value;
}
OUTPUT
Its been bugging me for hours because it is always returning 0 at numbers[i] and I cant figure out the problem. code worked for a different program but I had to change it so it could have a custom array size and that's when everything went wrong.
any help would be great.
Thanks in advance.
int[] numbers = new int[Convert.ToInt16(TxtArray.Text)];
int j = 0;
for (j = numbers.Length; j >= 0; j--)
{
int i = 0;
for (i = 0; i <= j - 1; i++)
{
string NumbersInput = Microsoft.VisualBasic.Interaction.InputBox("Enter Numbers to be sorted",
"Numbers Input", "", -1, -1);
numbers[i] = Convert.ToInt16(NumbersInput);
//returns 0 in if statement
if (numbers[i] < numbers[i + 1])
{
int intTemp = 0;
intTemp = numbers[i];
numbers[i] = numbers[i + 1];
numbers[i + 1] = intTemp;
}
}
}
for (int i = 0; i < numbers.Length; i++)
{
LstNumbers.Items.Add(numbers[i]);
}
private void button1_Click(object sender, EventArgs e)
{
int sizeOfArrayInt = Convert.ToInt32(arraySize.Text);
int[] array = new int[sizeOfArrayInt];
string numbers = arrayValues.Text;
string[] numbersSplit = numbers.Split(',');
int count = 0;
foreach (string character in numbersSplit)
{
int value;
bool parse = Int32.TryParse(character, out value);
if (value != null)
{
array[count] = value;
}
count++;
}
array = this.SortArray(array);
foreach (int item in array)
{
this.listBox.Items.Add(item);
}
}
private int[] SortArray(int[] arrayToSort)
{
//int[] sortedArray = new int[arrayToSort.Length];
int count = arrayToSort.Length;
for (int j = count; j >= 0; j--)
{
int i = 0;
for (i = 0; i <= j - 2; i++)
{
if (arrayToSort[i] < arrayToSort[i + 1])
{
int intTemp = 0;
intTemp = arrayToSort[i];
arrayToSort[i] = arrayToSort[i + 1];
arrayToSort[i + 1] = intTemp;
}
}
}
return arrayToSort;
}
strong text
This I got to work as a Windows Form and the output displays in the list box as each array item or individual i iteration over the array. Of course there is no error checking. Hope that helps.
Setting aside the strangeness of how you are working with text boxes, your problem with throwing an exception would happen even without them because it lies here, in your inner loop:
for (i = 0; i <= j - 1; i++)
Suppose that numbers.Length == 2. This means that j == 2. So on the first time through the outer loop, you hit the inner loop with these conditions. The first time through, i == 0. You get to the if statement:
if (numbers[i] < numbers[i + 1])
numbers[0] exists, and numbers[1] exists, so this iteration goes through fine and i is incremented.
Now i == 1. Now the loop checks its boundary condition. i <= j - 1 == true, so the loop continues. Now when you hit that if statement, it tries to access numbers[i + 1], i.e., numbers[2], which does not exist, throwing an IndexOutOfRangeException.
Edit: Came back and realized that I left out the solution (to the exception, anyway). For the bubble sort to work, your inner loop's boundary condition should be i <= j - 2, because j's initial value is == numbers.Length, which is not zero-based, while array indexes are.
Second Edit: Note that just using a List won't actually solve this problem. You have to use the right boundary condition. Trying to access list[list.Count()] will throw an ArgumentOutOfRangeException. Just because a List will dynamically resize doesn't mean that it will somehow let you access items that don't exist. You should always take time to check your boundary conditions, no matter what data structure you use.
I have a list of string arrays:
List<string[]> parsedRaw = new List<string[]>();
This list contains lines read in from a CSV, where parsedRaw[3][5] would be the fifth item read off the third line of the CSV.
I know that I can find the number of rows in the list with:
parsedRaw.Count
But, given a row, how can I find the number of elements in that row? I'm trying to implement a test before entering a loop to read from the list, in order to avoid an "Index was outside the bounds of the array" error, where the loop is:
for (k = 0; k < nBytes; k++)
{
TheseBytes[k] = (byte)parsedRaw[i][StartInt + k];
}
I'm encountering the error on a row in the CSV that has fewer elements than the others. Before entering this loop, I need to check whether parsedRaw[i] has at least "StartInt + nBytes" elements.
Thanks for any suggestions!
A row is just a string array string[], so you can find its size using the Length property of the array.
foreach (string[] row in parsedRaw) {
for (int i = 0 ; i != row.Length ; i++) {
// do something with row[i]
}
}
The number of elements in a given row is determined by
parsedRaw[theRowIndex].Length
To fix your for loop you need to constrain the StartInt + k value to be less than the minimum of nBytes and the row length
for (k = 0; (k < nBytes) && (k + StartInt < parsedRaw[i].Length); k++)
{
TheseBytes[k] = (byte)parsedRaw[i][StartInt + k];
}
Try
List<string[]> parsedRaw = new List<string[]>();
parsedRaw.Add(new string[] {"test1", "test2"});
parsedRaw.Add(new string[] { "test1", "test2", "test3" });
int totalSize = 0;
for (int i = 0; i < parsedRaw.Count(); i++)
{
int rowSize = 0;
for (int k = 0; k < parsedRaw[i].Count(); k++)
{
rowSize += parsedRaw[i][k].Length;
}
totalSize += rowSize;
}