Reputation: 779
I'm looping through the rows and columns of a DataSet to write to a text file with a pipe delimiter. I have it working except I need to leave off the pipe from the last column. Is there a way for me to adjust the loop to loop through fields.count-1 and then refer to the last field outside of the loop?
foreach (object item in row.ItemArray)
{
d = d+ item.ToString() + "|";
}
Upvotes: 2
Views: 343
Reputation: 1052
Only add a delimiter if your adding another value.
for(int i = 0; i < row.ItemArray.Length; i ++)
{
if( d.length == 0)
{
d = item.ToString();
}
else
{
d = d + "|" + item.ToString();
}
}
Upvotes: 0
Reputation: 131180
You can join the contents of any IEnumerable (including arrays) using String.Join, eg:
var newText = String.Join("|",row.ItemArray);
Upvotes: 6
Reputation: 2750
for(int i = 0; i < row.ItemArray.Length; i ++)
{
if(row.ItemArray[i] == row.itemArray[row.itemArray - 1])
{
d = d+ item.ToString();
}
else
{
d = d+ item.ToString() + "|";
}
}
Upvotes: 0
Reputation: 1683
You can just use the string.Join
method, as follows:
string.Join("|", row.ItemArray);
However, if you're doing other logic in the foreach
loop as well, consider using a StringBuilder
instead. This has huge performance gains over concatenating a string over and over again. Then, you can simply trim off the final pipe by adjusting it's length.
var d = new StringBuilder();
foreach (object item in row.ItemArray)
d.Append(item.ToString()).Append("|");
d.Length -= 1;
Upvotes: 1
Reputation: 144
after the loop:
d = d.remove(d.Count()-1);
This will remove the last character of your string.
Upvotes: 0
Reputation: 180787
You can use Linq Aggregate:
d = row.ItemArray.Aggregate((x, y) => x.ToString() + "|" + y.ToString());
Upvotes: 1
Reputation: 77846
You can use TrimEnd(Char[])
method like
d.TrimEnd(new char[]{'|'});
Upvotes: 1