排除循环中的最后一个元素 [英] Exclude last element in a loop

查看:116
本文介绍了排除循环中的最后一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

亲爱的朋友,

我的应用程序中存在一个循环.代码如下-

Dear Friend,

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

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



但是我不想在最后一个数据行中添加"\ n".
有什么建议怎么做吗?

问候
Saumitra.



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

Regards
Saumitra.

推荐答案

此代码可能对您有帮助

This code may help you

foreach (DataRow dr in dt.Rows)
        {
            ColorNames += ColorName + "\n";
        }
        ColorNames = ColorNames.Substring(0, (ColorNames.Length - 1));


好吧,foreach不是 迭代的唯一方法:
Well, you know, foreach is not the only way for iterating:
int i;
for (i = 0; i < dt.Rows.Count - 1; i++)
{
  DataRow dr = dt.Rows[i];
  ColorNames += dr["ColorName"].ToString() + "\n";
}
ColorNames += dt.Rows[i].dr["ColorName"];


您有很多答案可以使用,但是没有人解决您可能在此处进行很多字符串连接的事实.通常,如果要将多个元素附加在一起,则应考虑使用StringBuilder.您最终将得到的结果(使用CPallin的出色建议)是:
You have lots of answers to play with here, but nobody has addressed the fact that you may be doing lots of string concatenations here. In general, if you are going to be appending more than a couple of elements together, you should look into using a StringBuilder. What you would end up with (using CPallin''s excellent suggestion) is:
StringBuilder sb = new StringBuilder();
int count = dt.Rows.Count - 1;
for (int i = 0; i < count; i++)
{
  sb.AppendFormat("{0}\n", dt.Rows[i]["ColorName"].ToString());
}
sb.Append(dt.Rows[count]["ColorName"].ToString());
ColorNames = sb.ToString();

要考虑的另一件事是您应该使用\n还是Environment.NewLine.由于我不确定100%是否满足您的要求,因此我将留给您调查最适合您的需求.

Another thing to consider is whether you should be using \n or Environment.NewLine. As I''m not 100% sure what your requirements are there, I''ll leave it to you to investigate which is best suited to your needs.


这篇关于排除循环中的最后一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆