Removing trailing comma from CSV data - c#

This is the Code for adding comma after another number, but I want to delete the last comma:
str_MSISDN.Append("'" + _MSISDN[x].TrimStart() + "'" + ",");

Instead of manually appending things, I suggest you use String.Join which will get it right to start with. You can use LINQ to do the trimming of the values. For example:
string x = string.Join(",", _MSISDN.Select(x => "'" + x.TrimStart() + "'")
.ToArray());
EDIT: A nicer version of this is available with MoreLINQ and its ToDelimitedString method:
string x = _MSISDN.Select(x => "'" + x.TrimStart() + "'")
.ToDelimitedString(",");

You can do that using the TrimEnd method (when you are done appending):
str_MSISDN = str_MSISDN.ToString().TrimEnd(',');

You can use the String.TrimEnd() method:
[your value] = str_MSISDN.ToString().TrimEnd(",".ToCharArray())

My favourite way of doing this kind of thing is to use the string.Join method:
string str_MSISDN = string.Join(", ", _MSISDN);
(assuming that _MSISDN is an array of strings)
If you want to trim the start of each item you can do this:
string str_MSISDN = string.Join(", ", _MSISDN.Select(x=>x.TrimStart()).ToArray());
Note how you have to call .ToArray since the Join method wants an array not an IEnumerable

I'd say don't add it in the first place, you've several options for doing this.
1) Use string.join
2) Restructure your loop as follows
int i = 0;
if (_MSISDN.Length > 0)
{
str_MSISDN.Append("'" + _MSISDN[i++].TrimStart() + "'")
while( i < _MSISDN.Length )
str_MSISDN.Append(",'" + _MSISDN[i++].TrimStart() + "'");
}

Related

C# - Add a whitespace between two strings

I have code to display a vehicle by its Make and Model.
productName.Text = p.Make + p.Model
The above code displays the text as such: "BentleyContinental", how can I make the text display as such "Bentley Continental".
You can use string.Format():
productName.Text = string.Format("{0} {1}", p.Make, p.Model);
Or you can use string interpolation (if you are on C# 6 or higher):
productName.Text = $"{p.Make} {p.Model}";
Or you can do just as you have (string concatenation) but add in a space:
productName.Text = p.Make + " " + p.Model;
Use the string.concat method to concatenate string parts.
productName.Text = string.concat(p.Make, " ", p.Model);
In general, you use the string.concat when you know you'll add less than a dozen parts. More than that, or if you are in a loop, there is more benefits using the StringBuilder class.
productName.Text = p.Make + " " + p.Model
Just concatenate a space between two words. I think this is the easiest way.

Incrementer not working inside string replace

I'm attempting to read a line from a file (csv header) and create a column list that prepends "c[num]_" in front of each column with this code:
int colCount=0;
string line = "col1,col2,col3,col4,col5";
string ColumnList = "([" + (++colCount).ToString() + "_" + line.Replace(",", "],[c" + (++colCount).ToString() + "_") + "]";
I know it's not elegant, but I'm also not sure why my colCount variable doesn't increment inside the replace?? It results with a string like:
([c0_col1],[c1_col2],[c1_col3],[c1_col4],[c1_col5])
The counter increments the first time and then not again inside the replace. Any insights? I think it might be better written with a Regex ReplaceEvaluator but I haven't been able to piece that together yet either.
The paramter of the Replace method is string, and the expression you've entered there is just a string. The count will always be 2. It's not a Func, it a string.
You can use the following Linq to easily achieve the conversion you'd like:
string ColumnList = string.Join(",", line.Split(',').Select((s, i) => $"[c{i + 1}_{s}]"));

Last item in the c# list

I am need to highlight the keywords or tags in an article & pass variable to jQuery Array
i am using property to pass value from C# to java-script which works i also need to format my keywords which in database are stored like one, two, three, four, five,six,seven
in order to make it work i have to wrap each keyword in single ' or double quotes".
JQuery
function HighlightKeywords(keywords) {
var el = $("body");
$(keywords).each(function () {
var pattern = new RegExp("(" + this + ")", ["gi"]);
var rs = "<a href='search.aspx?search=$1'<span style='background-color:#FFFF00;font-weight: bold;background-color:#FFFF00;'>$1</span></a>";
el.html(el.html().replace(pattern, rs));
});
}
HighlightKeywords(["<%= MyProperty %>]");
C# Code
string _sFinalList = null;
protected string MyProperty { get { return _sFinalList; } }
string sKewords = "one, two, three, four, five,six,seven";
List<string> lstKewords = sKewords.Split(',').ToList();
foreach (string list in lstKewords) // Loop through List with foreach
{
_sFinalList += "'" + list + "',";
}
Problem with this code is that it ads , after the last words i want to know what is the best way to avoid adding , after the last words
Current OUTPUT: "'one', 'two', 'three', 'four', 'five','six','seven',"
Desired OUTPUT: "'one', 'two', 'three', 'four', 'five','six','seven'"
Help in this regard is appreciated
In C#, use String.Join() :
List<string> lstKeywords = sKeywords.Split(',').ToList();
var quotedKeywords = lstKeywords.Select(s => "'" + s + "'");
string _sFinalList = string.Join(",", quotedKeywords);
You can using String.Join()
string sKewords = "one, two, three, four, five,six,seven";
List<string> lstKewords = sKewords.Split(',').ToList();
var _partial = lstKewords.Select(x => "'" + x + "'");
Var _result = String.Join(",", _partial);
String.Join()
You could use String.Join
var result = string.Format("'{0}'", string.Join("','", yourList));
you may simply remove lastIndexOf(",") with substring function of string class after you complete the for loop.
OR
you may add and if statement in your for loop that would add "," if loop is not in its last iteration.

c# Using Substring and Regular Expressions to edit a large string

The string, when displayed looks like: value1, value2, value3, value4, value5 etc..
What I want the string to do once I display it is (removing spaces and commas, i assume I can use index + 2 or something to get past the comma):
value1
value2
etc...
lastKnownIndexPos = 0;
foreach (System.Text.RegularExpressions.Match m in System.Text.RegularExpressions.Regex.Matches(unformatedList, ",?")) //Currently is ',' can I use ', '?
{
list += unformatedList.Substring(lastKnownIndexPos, m.Index - 1) + "\n\n"; //-1 to grab just the first value.
lastIndex = m.Index + 2; //to skip the comma and the space to get to the first letter of the next word.
//lastIndex++; //used this to count how many times it was found, maxed at 17 (have over 100):(
}
//MessageBox.Show(Convert.ToString(lastIndex)); //used to display total times each was found.
MessageBox.Show(list);
At the moment the message box does not show any text, but using the lastIndex I get a value of 17 so I know it works for part of it :P
That's easy (I'm using System.Linq here):
var formatted = string.Join("\n\n", unformatedList.Split(',').Select(x => x.Trim()));
MessageBox.Show(formatted);
An alternative approach, as swannee pointed out, would be the following:
var formatted = Regex.Replace(unformatedList, #"\s*,\s*", "\n\n").Trim();
Edit:
To make the above examples work regardless of how you use the result string, you should use Environment.NewLine instead of "\n".
One way is to simply replace the ", " with a newline.
MessageBox.Show( unformatedList.Replace(", ", "\n") );
Or heck, why not just use string.Replace?
var formatted = unformattedList.Replace(", ", "\n\n");

Generating Comma Separated Values

Suppose I have a collection of strings:
"foo"
"bar"
"xyz"
And I would like to generate a comma separated values from the list into something like:
"foo, bar, xyz"
Notice the lack of ", " at the end.
I am aware that there are dozens of ways to generate this:
use for-loop and string.Format() or StringBuilder.
use integer counter and remove the ending ", " if the value > 0
don't put ", " on the first run
etc.
Sample code of what I have right now:
if (strs.Count() > 0)
{
var sb = new StringBuilder();
foreach (var str in strs)
sb.AppendFormat("{0}, ", str);
return sb.Remove(0, 2).ToString();
}
What is the best code that is highly reusable for the above scenario, and why?
You want to use the string.Join method, which exists in the BCL for this purpose.
Example:
var myArray = new string[] { "one", "two", "three" };
var output = string.Join(", ", myArray);
Or if you're using .NET 3.5, you can do this with any IEnumerable<string> as such:
var output = string.Join(", ", myEnumerable.ToArray());
(Note that this doesn't give the best performance as it requires, although it is clearly still 'O(n)', and should be suitable for almost all cases).
Now, if your enumerable is not of type string (generically an IEnumerable<T>), you can just use the Select method to convert the result into a string, e.g.
var output = string.Join(", ", myEnumerable.Select(e => e.ToString()).ToArray());
I'm not sure if you're dealing with values that may potentially contains commas in themselves, but this can be worked around by enclosing them in quotes (") and escaping the quotes, similarly to the CSV format.
var output = string.Join(", ", items.Select(x => x.Contains(",") ?
"\"" + x.Replace("\"", "\"\"") + "\"" : x);
Of course, splitting them back up again is a slightly triciker task, which requires a bit of regex.
String.Join is the right answer, but in the case of an IEnumerable, Linq is often shorter than a for loop:
someStringCollection.Aggregate((first, second) => first + ", " + second);
As others have said: String.Join is normally the best way to do this. But what if you have just have an IEnumerable rather than an array? Perhaps you have code to enumerate these as you read them from a file using deferred execution. In this case String.Join isn't quite as nice, because you have to loop over the strings twice — once to create the array and once to join it. In that case, you want something more like this:
public static string ToDelimitedString(this IEnumerable<string> source, string delimiter)
{
string d = "";
var result = new StringBuilder();
foreach( string s in source)
{
result.Append(d).Append(s);
d = delimiter;
}
return result.ToString();
}
This will perform almost as well as String.Join, and works in the more general case. Then, given a string array or any other IEnumerable you can call it like this:
string finalStr = MyStrings.ToDelimitedString(",");
string finalstr = String.Join(",", strs);
Use
string s = string.Join (",", new string[] {"aaa", "bbb", "ccc"});
Use String.Join
If you have an array of strings, go with Noldorin's solution.
But if it's some other collection type, I might do this:
if (strs.Count() > 0)
{
var sb = new StringBuilder();
foreach (var str in strs)
sb.AppendFormat("{0} {1}", (0 == sb.Length ? "" : ","), str);
return sb.ToString();
}

Categories