s.k.paul
s.k.paul

Reputation: 7291

Exclude last element in a loop

I have a loop in my app. Code is following :-

foreach (DataRow dr in dt.Rows)
    ColorNames +=dr["ColorName"].ToString() + "\n";

But i don't want to add \n at the last Datarow. Any suggestion how to do it?

Upvotes: 2

Views: 1931

Answers (4)

Nikhil Agrawal
Nikhil Agrawal

Reputation: 48568

Foreach do not work on index.

Option 1: ForEach Loop

Use foreach loop. Loop till last and outside loop do like

ColorNames.Substring(0, ColorNames.Length-1);

Option 2: For Loop

Use for loop and check for index inside loop for all indexes till last. add \n and in last index do not add \n

for (int i = 0; i < dt.Rows.Count; i++)
{
   ColorNames += i < dt.Rows.Count-1 
           ? dr["ColorName"].ToString() + "\n"
           : dr["ColorName"].ToString();
}

OR

for (int i = 0; i < dt.Rows.Count; i++)
   ColorNames += dr["ColorName"].ToString() + (i < dt.Rows.Count-1 ?  "\n": "");

Option 3: LINQ

ColorNames = String.Join("\n", dt.Rows.Select(dr => dr["ColorName"].ToString()));

Upvotes: 2

Darshana
Darshana

Reputation: 2548

int count = 0;
foreach (DataRow dr in dt.Rows)
{
    count++;
    ColorNames +=dr["ColorName"].ToString();
    if (count < dt.Rows.Count)
        ColorNames += "\n";
}

Upvotes: 0

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236218

ColorNames = String.Join("\n", dt.Rows.Select(dr => dr["ColorName"].ToString()));

Here is updated version (forgot that cast to Enumerable needed):

ColorNames = String.Join("\n", dt.AsEnumerable().Select(dr => dr.Field<string>("ColorName")));

Upvotes: 8

Geert Baeyaert
Geert Baeyaert

Reputation: 303

var colorNamesList = dt.Rows
  .Cast<DataRow>()
  .Select(dr => dr["ColorName"].ToString())
  .ToArray();

var colorNames = String.Join("\n", colorNames);

Upvotes: 0

Related Questions