I want to remove the first comma. Is there a way to remove the comma of the loop?
Here's my code:
foreach (var field in tablefields.Items)
{
if (m_datacount < datatype.Items.Count)
{
d_type = datatype.Items[m_datacount].ToString();
m_datacount++;
}
richTextBox1.Text = richTextBox1.Text + "\t,#" + field + " " + d_type + "\n";
datatype.ResetText();
}
m_datacount = 0;
Output:
,#id uniqueidentifier
,#title varchar
,#active_flag bit
,#created_by_id uniqueidentifier
,#created_by_system_code varchar
,#created_date_time datetime
,#modified_by_id uniqueidentifier
,#modified_by_system_code varchar
,#modified_date_time datetime
Why reinvent the wheel....
Simply use String.Join
string result = String.Join(", ", myarray);
for e.g.
string[] myarray = { "Firstuser", "Seconduser" };
So result will be "Firstuser, Seconduser",
I would use String.Join. Since you have commented on another answer that tablefields is a ListBox this works:
var strings = tablefields.Items.Cast<object>().Select(o => o.ToString());
richTextBox1.Text = String.Join(Environment.NewLine + ",", strings);
Tested with this sample data:
tablefields.Items.AddRange(new ListBox.ObjectCollection(tablefields, new[]{"id","spid","charge_type_rcd","name_e","active_status"}));
Output:
id
,spid
,charge_type_rcd
,name_e
,active_status
You can also use a StringBuilder which is less readable but can be more efficient if you have many, many items:
StringBuilder sb = new StringBuilder();
foreach (var item in tablefields.Items)
sb.AppendLine(item.ToString()).Append(',');
if (sb.Length > 0) sb.Length--; // to remove the last comma
richTextBox1.Text = sb.ToString();
TrimEnd method can be used to remove trailing characters from a string:
richTextBox1.Text = richTextBox1.Text.TrimEnd(',');
you can use below menioned code
richTextBox1.Text = richTextBox1.Text.Substring(0,richTextBox1.Text.Length-1);
What is the purpose of field2? It isn't used in your code...
Why use a counter (m_fieldcount) if you're using a foreach loop?
What does tablefields.ResetText(); do?
Anyway, try this:
richTextBox1.Text = String.Join("\n\t,", tablefields.Items.Select(a=>a.ToString()).ToArray());
richTextBox1.Text + "" + t_fields + "\n\t,".Remove(richTextBox1.Text.Lenght - 1);
check out also removing the last index. using Remove(index)
Related
I have a string like this in C#:
string a = "A|B|C|D"
I want to split this string on the pipe character and prepend some text to each entry. Currently, I am doing a split like this:
string[] result = a.Split('|')
But because the string array is of a fixed size, I need to create a new array and copy the prepended result using a for loop. Is there a Linq way or a one-liner to achieve this instead of writing a for loop? In Python, I would have done a one-liner for loop:
newresult = ["Prepend string " + x for x in result]
Any suggestions?
var newResult = a.Split('|').Select(x => "Prepend string " + x).ToArray();
I found this to be easy enough, if you say want to join it back too:
string.Join(" , ", devices.Select(s => "PREFIX = " + s).ToArray());
Not sure why you need to create a new array, but first the Linq method is to use the .Select operator:
stirng[] result = a.Split('|').Select(x => "Prepend string " + x).ToArray();
That said, you could also just edit the array inline (i.e. no need for a new array):
for (var i = 0; i < result.Length; i++)
result[i] = "Prepend string " + result[i];
I needed to merge strings that are inside List<string> together into oneliner. I came up with simple solution but I am not sure if it's the best way to go.
First version with problematic , on string start:
string benchmarkiUjemneDatyRazem = "";
foreach (string s in benchmarkiUjemne) {
benchmarkiUjemneDatyRazem = benchmarkiUjemneDatyRazem + "," + s;
}
Second version (Linq power) but still with ` :
string benchmarkiUjemneDatyRazem = benchmarkiUjemne.Aggregate("", (current, s) => current + "," + s);
Working version without , but amount of lines makes some pain in later reading it:
int b = 0;
string benchmarkiUjemneDatyRazem = "";
foreach (string s in benchmarkiUjemne) {
if (b == 0) {
b = 1;
benchmarkiUjemneDatyRazem = s;
continue;
}
benchmarkiUjemneDatyRazem = benchmarkiUjemneDatyRazem + "," + s;
}
Final version that I came up with was based on Linq with Subsitute to first char:
string benchmarkiUjemneDatyRazem = benchmarkiUjemne.Aggregate("", (current, s) => current + "," + s).Substring(1);
Is this good approach to this problem ? Or there's better way to actually do it? Like using StringBuilder or so?
If you're using .Net 4, you can use string.Join (in earlier versions this will work only if benchmarkiUjemne is a string[]):
string result = string.Join(",", benchmarkiUjemne);
If this is .Net 3.5 or older, you can still use it by calling ToArray on the list:
string result = string.Join(",", benchmarkiUjemne.ToArray());
Use string.Join:
var res = string.Join(",", benchmarkiUjemne);
i have this code which should insert all elements of array which is some html on random places in a string. but it only inserts last element to that string. please help
Random insertPos = new Random();
int pos = insertPos.Next(txtInput.Text.Length);
int firSpace= txtInput.Text.IndexOf(" ", pos);
int secSpace = txtInput.Text.IndexOf(" ", firSpace+1);
int wLen = secSpace - firSpace;<br/>
string word = txtInput.Text.Substring(firSpace,wLen);
foreach (string url in urlArray)
{
txtOutput.Text =
txtInput.Text.Replace(word, "" + word + "");
}
You are replacing (=) the contents of txtOutput.Text on every iteration so of course you are only going to see the last result. Consider using +=1 first to get it working and then a StringBuilder if your performance is suffering and this is a bottleneck.
1: It's not clear exactly how you want it formatted, but at least += will append and assign the result of the append instead of just the result of the current iteration.
You overwrite the Text property of the textbox in every step of the foreach loop. Only the result of last loop will be left.
You are repeatedly saying "figure out what happens when I insert the HTML into txtInput 's text, and assign the result to the txtOutput text". But this does not actually change the text in txtInput, so you are starting fresh each time; and you throw away the txtOutput text each time to replace it with the new stuff.
As Jaison said you are using = instead of +=, but there are better solutions. Remember that strings are immutable. Use string.Format or StringBuilder where you're concatenating strings. Examples:
string[] strArray = {"a", "b", "c"};
string word = "word";
//1st solution +=
string output = "";
foreach (string str in strArray)
output += "" + word + "";
Console.WriteLine(output);
//better solution string.Format
output = "";
foreach (string str in strArray)
output += string.Format("{1}", str, word);
Console.WriteLine(output);
//StringBuilder
StringBuilder sb = new StringBuilder();
foreach (string str in strArray)
sb.AppendFormat("{1}", str, word);
output = sb.ToString();
Console.WriteLine(output);
//linq & string.Join
output = string.Join("", strArray.Select( str => string.Format("{1}", str, word)).ToArray());
Console.WriteLine(output);
Console.Read();
I am creating concatenated strings based on the data in each row of my ListView control. I need to figure out how to remove the first element in each string which pertains to a single row of the ListView. How might I accomplish this? This is a C# winforms project.
Here is my current code:
foreach (ListViewItem HazPackErrItems in HazmatPackageErrorListview.Items)
{
string HazPackErrRow = " ";
foreach (ListViewItem.ListViewSubItem HazPackErrSub in HazPackErrItems.SubItems)
{
HazPackErrRow += " " + HazPackErrSub.Text + ",";
}
// Remove comma after last element of string.
HazPackErrRow = HazPackErrRow.Substring(0, HazPackErrRow.Length - 2);
MessageBox.Show(HazPackErrRow); // List concatenated subitems
}
Just don't add it in the first place?
foreach (ListViewItem HazPackErrItems in HazmatPackageErrorListview.Items)
{
string HazPackErrRow = " ";
bool first = true;
foreach (ListViewItem.ListViewSubItem HazPackErrSub in HazPackErrItems.SubItems)
{
if (first)
first = false;
else
HazPackErrRow += " " + HazPackErrSub.Text + ",";
}
// Remove comma after last element of string.
HazPackErrRow = HazPackErrRow.Substring(0, HazPackErrRow.Length - 2);
MessageBox.Show(HazPackErrRow); // List concatenated subitems
}
If you can use Linq, use String.Join(), it reads a lot easier:
foreach (ListViewItem HazPackErrItems in HazmatPackageErrorListview.Items)
{
string HazPackErrRow = string.Join(", ", HazPackErrItems.SubItems.Skip(1).Select(s => s.Text).ToArray())
MessageBox.Show(HazPackErrRow); // List concatenated subitems
}
This is based on Inferis's answer, but it uses a StringBuilder and avoids the need for the final Substring call:
foreach (ListViewItem errors in HazmatPackageErrorListview.Items)
{
StringBuilder builder = new StringBuilder();
bool first = true;
foreach (ListViewItem.ListViewSubItem error in errors.SubItems)
{
if (first)
{
first = false;
}
else
{
if (builder.Length > 0)
{
builder.Append(", ");
}
builder.Append(error.Text);
}
}
MessageBox.Show(builder.ToString()); // List concatenated subitems
}
Here's an alternative way of tackling the delimiter issue:
foreach (ListViewItem errors in HazmatPackageErrorListview.Items)
{
StringBuilder builder = new StringBuilder();
bool first = true;
string prefix = "";
foreach (ListViewItem.ListViewSubItem error in errors.SubItems)
{
if (first)
{
first = false;
}
else
{
builder.Append(prefix);
prefix = ", ";
builder.Append(error.Text);
}
}
MessageBox.Show(builder.ToString()); // List concatenated subitems
}
Of course, there's a simpler way:
foreach (ListViewItem errors in HazmatPackageErrorListview.Items)
{
string[] bits = errors.SubItems.Skip(1)
.Select(item => item.Text)
.ToArray();
string errorLine = string.Join(", ", bits);
MessageBox.Show(errorLine);
}
You can use IList<T>.Skip():
foreach (var HazPackErrSub in HazPackErrItems.SubItems.Skip(1))
Because other people seem to be rewriting your code, why not I? =]
foreach(ListViewItem HazPackErrItems in HazmatPackageErrorListview.Items)
{
string HazPackErrRow = String.Join(", ", HazPackErrItems.SubItems.Skip(1).Select(t => t.Text).ToArray());
MessageBox.Show(HazPackErrRow); // List concatenated subitems
}
If I understand the problem correctly, you could just use a for loop and start the index at 1 instead of 0.
add the comma at the beginning, then you only have to do one check, rather than a check on every iteration
string HazPackErrRow = "";
foreach (ListViewItem.ListViewSubItem HazPackErrSub in HazPackErrItems.SubItems)
{
HazPackErrRow += "," + " " + HazPackErrSub.Text;
}
// Remove comma before first element of string.
if(HazPackErrRow.Length > 0)
HazPackErrRow = HazPackErrRow.Substring(1);
Edit:
Um, ignore me, I misread the question.
I have a program where an array gets its data using string.Split(char[] delimiter).
(using ';' as delimiter.)
Some of the values, though, are null. I.e. the string has parts where there is no data so it does something like this:
1 ;2 ; ; 3;
This leads to my array having null values.
How do I get rid of them?
Try this:
yourString.Split(new string[] {";"}, StringSplitOptions.RemoveEmptyEntries);
You could use the Where linq extension method to only return the non-null or empty values.
string someString = "1;2;;3;";
IEnumerable<string> myResults = someString.Split(';').Where<string>(s => !string.IsNullOrEmpty(s));
public static string[] nullLessArray(string[] src)
{
Array.Sort(src);
Array.Reverse(src);
int index = Array.IndexOf(src, null);
string[] outputArray = new string[index];
for (int counter = 0; counter < index; counter++)
{
outputArray[counter] = src[counter];
}
return outputArray;
}
You should replace multiple adjacent semicolons with one semicolon before splitting the data.
This would replace two semicolons with one semicolon:
datastr = datastr.replace(";;",";");
But, if you have more than two semicolons together, regex would be better.
datastr = Regex.Replace(datastr, "([;][;]+)", ";");
words = poly[a].Split(charseparators, StringSplitOptions.RemoveEmptyEntries);
foreach (string word in words)
{
richTextBox1.Text += (d + 1)+ " " + word.Trim(',')+ "\r\n";
d++;
}
charseparators is a space