How to separate objects in a hidden input? - c#

I have a hidden input that contains some objects in it. I put string "#" between any two objects, but I want to put a string that isn't on keyboard. How can I do it?
for (int i = 0; i < MyTable.Rows.Count; i++)
{
txtRows.Value += MyTable.Rows[i]["Row"].ToString();
if (i < MyTable.Rows.Count - 1)
{
txtRows.Value += "#";
}
}

You can put any character you like in between two strings. For example to use the ASCII record separator character, use this:
if (i < MyTable.Rows.Count - 1)
{
txtRows.Value += '\x1e';
}
And then split the value back into multiple strings using the Split method:
string[] values = txtRows.Split('\x1e');
However, I'd recommend using an array or list of inputs instead:
for (int i = 0; i < MyTable.Rows.Count; i++)
{
txtRows[i].Value = MyTable.Rows[i]["Row"].ToString();
}
Of course, you'll probably have to modify how you add these hidden elements to your form, but it's a much nicer way of handling these sorts of problems.

Related

PadRight in string of arrays doesn't add chars

I created array of strings which includes strings with Length from 4 to 6. I am trying to PadRight 0's to get length for every element in array to 6.
string[] array1 =
{
"aabc", "aabaaa", "Abac", "abba", "acaaaa"
};
for (var i = 0; i <= array1.Length-1; i++)
{
if (array1[i].Length < 6)
{
for (var j = array1[i].Length; j <= 6; j++)
{
array1[i] = array1[i].PadRight(6 - array1[i].Length, '0');
}
}
Console.WriteLine(array1[i]);
}
Right now the program writes down the exact same strings I have in array without adding 0's at the end. I made a little research and found some informations about that strings are immutable, but still there are some example with changing strings inside, but I couldn't find any with PadRight or PadLeft and I fell like there must be a way to do it, but I just can't figure it out.
Any ideas on how to fix that issue?
The first argument to PadRight is the total length you want. You've specified 6 - array1[i].Length - and as all your strings start off with at least 3 characters, you're padding to at most 3 characters, so it's not doing anything.
You don't need your inner loop, and your outer loop condition is more conventionally written as <. This is one way I'd write that code:
using System;
public class Test
{
static void Main()
{
string[] array =
{
"aabc", "aabaaa", "Abac", "abba", "acaaaa"
};
for (var i = 0; i < array.Length; i++)
{
array[i] = array[i].PadRight(6, '0');
Console.WriteLine(array[i]);
}
}
}
In fact I'd probably use foreach, or even Select, but that's a different matter. I've left this using an array to be a bit closer to your original code.

Remove text after a loop

I have a for loop that adds a radiobutton text at the end of a string. Here is the code:
for (int i = 0; i < listView1.CheckedItems.Count; i++)
{
sqlQry.Text += listView1.CheckedItems[i].Text + radioButton9.Text;
}
is there a way to trim the radioButton9.Text after the loop ends?
Something like:
sqlQry.Text = sqlQry.Text.TrimEnd(',');
Right now the Result is something like: "A and B and C and"
I want it to be: "A and B and C"
I did try the code i mentioned but i cannot use:
sQlQry.Text=sqlQry.Text.TrimEnd(radioButton9.Text);
You could use string.Join
sqlQry.Text = string.Join(radioButton9.Text, listView1.CheckedItems.Cast<ListViewItem>().Select(x => x.Text));
It is a lot easier to use a different logic so that you don't put the separator there at the end in the first place.
for (int i = 0; i < listView1.CheckedItems.Count; i++)
{
if(i != 0)
{
// Put separator in before this thing
// when this is not the first thing we add.
sqlQry.Text += radioButton9.Text;
}
sqlQry.Text += listView1.CheckedItems[i].Text;
}
You can get the Length of radioButton9.Text and do a Substring of
your sqlQry.Text
sqlQry.Text.Substring(0, sqlQry.Text.Length - radioButton9.Text.Length);
Simple solution: string.Substring(startIndex, length).
Example: sqlQry.Substring(0, sqlQry.Length - /*fixedLength*/ radioButton9.Text.Length)
This returns a string which takes off a fixed amount of characters from the end. Updated takes off the length of the radioButton9's text property's length.

Comparing a part of a string. C#

I want to compare and check if a string is a part of another string. For example:
String1 = "ACGTAAG"
String2 = "TAA"
I want to check if String1 contains String2. Im using this code but it does not work.
public bool ContainsSequence(string input, string toBeChecked)
{
for (int i = 0; i < input.Length; i++)
{
Char x = input[i];
String y = Convert.ToString(x);
for (int j = 0; j < toBeChecked.Length; j++)
{
Char a = toBeChecked[j];
String b = Convert.ToString(a);
if (b.Equals(y))
{
j = toBeChecked.Length;
return true;
}
}
}
return false;
}
input = string1 and tobechecked = string 2.
Im new in c# so some terms may be confusing.
try use String.Contains()
Check it out here:
http://msdn.microsoft.com/en-us/library/dy85x1sa%28v=vs.110%29.aspx
Good luck.
Use
If(mainString.Contains(searchedString)
{
//do stuff
}
It looks to me like you're using this to compare DNA sequences :).
Maybe string.IndexOf(string value) or one of it's overloads is better for you because it can help
you search for further occurences of the same string (stuff like "how many times does it contain the string"): http://msdn.microsoft.com/en-us/library/k8b1470s(v=vs.110).aspx
If indeed all you want is just to see if the string is contained, I'd also go for the versions provided by the others.
For nucleotide sequences you probably want some sequence alignment algorithm which has some tolerance when sequences are not equal. For example Smith–Waterman algorithm.

Performance issues with nested loops and string concatenations

Can someone please explain why this code is taking so long to run (i.e. >24 hours):
The number of rows is 5000, whilst the number of columns is 2000 (i.e. Approximately 10m loops).
Is there a better way to do this????
for (int i = 0; i < m.rows; i++)
{
for (int j = 0; j < m.cols; j++)
{
textToWrite += m[i, j].ToString() + ",";
}
//remove the final comma.
textToWrite = textToWrite.Substring(0,textToWrite.Length-2);
textToWrite += Environment.NewLine;
}
Yes, the += operator is not very efficient. Use StringBuilder instead.
In the .NET framework a string is immutable, which means it cannot be modified in place. This means the += operator has to create a new string every time, which means allocating memory, copying the value of the existing string and writing it to the new location. It's ok for one or two concatenations, but as soon as you put it in a loop you need to use an alternative.
http://support.microsoft.com/kb/306822
You'll see a massive performance improvement by using the following code:
var textToWriteBuilder = new StringBuilder();
for (int i = 0; i < m.rows; i++)
{
for (int j = 0; j < m.cols; j++)
{
textToWriteBuilder.Append(m[i, j].ToString() + ",");
}
// I've modified the logic on the following line, I assume you want to
// concatenate the value instead of overwriting it as you do in your question.
textToWriteBuilder.Append(textToWriteBuilder.Substring(0, textToWriteBuilder.Length - 2));
textToWriteBuilder.Append(Environment.NewLine);
}
string textToWrite = textToWriteBuilder.ToString();
Because you are creating tons of strings.
You should use StringBuilder for this.
StringBuilder sb = new StringBuildeR();
for (int i = 0; i < m.rows; i++)
{
bool first = true;
for (int j = 0; j < m.cols; j++)
{
sb.Append(m[i, j]);
if (first)
{
first = false;
}
else
{
sb.Append(",");
}
}
sb.AppendLine();
}
string output = sb.ToString();
Your code is taking so long because you're appending strings, creating thousands of new temporary strings as you go. The memory manager needs to find memory for these strings (which increase in memory requirements, as they get longer) and the operation copies the characters you have so far (the number of which increases with every iteration) to the newest string.
The alternative is to use a single StringBuilder, on which you call Append() to append more efficiently and, finally, ToString() when you're done to get the finalized string that you want to use.
The biggest issue I see with this is the fact you're using textToWrite as a string.
As strings are immutable so each time the string is changed new memory must be reserved copied from the previous version.
A far more efficient approach is to use the StringBuilder class which is designed for exactly this type of scenario. For example:
StringBuilder sb = new StringBuilder();
for (int i = 0; i < m.rows; i++)
{
for (int j = 0; j < m.cols; j++)
{
sb.Append(m[i, j].ToString());
if(j < m.cols - 1) // don't add a comma on the last element
{
sb.Append(",");
}
}
sb.AppendLine();
}
Supposing that textToWrite is a String, you should use StringBuilder instead. String is immutable and it is very ineffective to add small parts.
Ideally you would initialize StringBuilder with a reasonable size (see doc).
Use a StringBuilder instead of several million concatenations.
If you concatenate 2 strings, this means the system allocates new memory to contain both of them, and then copies both in. A zillion large memory allocations and copy actions become slow very fast.
What StringBuilder does is reduce this immensely by allocating 'in advance', thus only having to grow the buffer a few times and just copying it in, eliminating the by far slowest factor of your loop.
Assume the matrix is of size MxM and has N elements. You are building the string in a way that takes O(N^2) (or O(M^4)) in the number of iterations. Each operation must copy what's already there. The issue is not some constant-factor overhead like temporary strings.
Use StringBuilder.
String concatenation is more efficient for small number of concatenated strings. For a dynamic number of strings, use StringBuilder.
The reason that it takes so long to run is because you are using string concatenation to create a string. For each iteration it will copy the entire string to a new string, so in the end you will have copied strings that adds up to several million times the final string.
Use a StringBuilder to create the string:
StringBuilder textToWrite = new StringBuilder();
for (int i = 0; i < m.rows; i++)
{
for (int j = 0; j < m.cols; j++)
{
if (j > 0) textToWrite.Append(',');
textToWrite.Append(m[i, j]);
}
textToWrite.AppendLine();
}

How can I change numbers into letters in C#

I have code like this:
for (int i = 1; i < max; i++)
{
<div>#i</div>
<div>#test[i]</div>
}
I'm using MVC3 razor syntax so it might look a bit strange.
My max is always less than ten and I would like to have a value like "A", "B" .. etc appear between the first instead of the number "1", "2" .. which is the value of i. Is there an easy way I can convert i to a letter where i = 1 represent "A" and i=2 represents "B". I need to do this in C# which I can place in my MVC3 view file.
Marife
Personally I'd probably use the indexer into a string:
// Wherever you want to declare this
// As many as you'll need - the "X" is to put A=1
const string Letters = "XABCDEFGHIJKLMNOP";
...
<div>
for (int i = 1; i < max; i++)
{
<div>#i</div>
<div>#Letters[i]</div>
}
I find that simpler and more flexible than bit shifting etc, although that will certainly work too.
(char)(i + 64) will work (65 = 'A')
for (int i = 1; i < max; i++)
{
char c = (char)(i + 64); // c will be in [A..J]
...
}
You could shift i by 64 (with a 1-based index) and cast your int to a char.
If you don't need to use i anywhere else you can do this:
for (Char ch = 'A'; ch < 'K'; ch++)
{
MessageBox.Show(ch.ToString());
}
Ah, just realised the last letter isn't constant, so you would need to convert a number somwwehere.

Categories