Leehbi
Leehbi

Reputation: 779

Looping through a dataset

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

Answers (8)

Shaun07776
Shaun07776

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

Panagiotis Kanavos
Panagiotis Kanavos

Reputation: 131180

You can join the contents of any IEnumerable (including arrays) using String.Join, eg:

var newText = String.Join("|",row.ItemArray);

Upvotes: 6

Pat
Pat

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

entropic
entropic

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

Brent Zundel
Brent Zundel

Reputation: 144

after the loop:

d = d.remove(d.Count()-1);

This will remove the last character of your string.

Upvotes: 0

Luke
Luke

Reputation: 150

You can use:

string.Join("|", row.ItemArray);

Upvotes: 1

Robert Harvey
Robert Harvey

Reputation: 180787

You can use Linq Aggregate:

d = row.ItemArray.Aggregate((x, y) => x.ToString() + "|" + y.ToString());

Upvotes: 1

Rahul
Rahul

Reputation: 77846

You can use TrimEnd(Char[]) method like

d.TrimEnd(new char[]{'|'});

Upvotes: 1

Related Questions