1

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?

Nikhil Agrawal
  • 44,717
  • 22
  • 115
  • 201
s.k.paul
  • 6,663
  • 24
  • 88
  • 159
  • possible duplicate of [Identifying last loop when using for each](http://stackoverflow.com/questions/1068110/identifying-last-loop-when-using-for-each) – Henk Holterman May 10 '12 at 11:13

4 Answers4

8
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")));
Sergey Berezovskiy
  • 224,436
  • 37
  • 411
  • 441
2

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()));
Nikhil Agrawal
  • 44,717
  • 22
  • 115
  • 201
0
var colorNamesList = dt.Rows
  .Cast<DataRow>()
  .Select(dr => dr["ColorName"].ToString())
  .ToArray();

var colorNames = String.Join("\n", colorNames);
Nikhil Agrawal
  • 44,717
  • 22
  • 115
  • 201
Geert Baeyaert
  • 293
  • 1
  • 4
0
int count = 0;
foreach (DataRow dr in dt.Rows)
{
    count++;
    ColorNames +=dr["ColorName"].ToString();
    if (count < dt.Rows.Count)
        ColorNames += "\n";
}
Darshana
  • 2,416
  • 6
  • 26
  • 50