用分隔符连接字符串的有效方法
本文关键字:有效 方法 字符串 分隔符 连接 | 更新日期: 2023-09-27 18:01:48
foreach (SessionTeacher sessionTeacher in sessionTeachers)
{
Person person = EMS.PWDAL.DALHelper.GetPersonByID(sessionTeacher.PersonID);
ltrlSpeakers.Text += person.Name1 + ", ";
}
这里的ltrlSpeakers.Text
是这样的"abc, def, "这是我必须删除的额外的逗号和空格。
// removing extra comma and space
ltrlSpeakers.Text = ltrlSpeakers.Text.ToString().Remove(ltrlSpeakers.Text.ToString().Length - 2, 2);
它工作得很好,但有没有更好更有效的简单方法?
像这样:
var personNames = sessionTeachers.Select(
st => EMS.PWDAL.DALHelper.GetPersonByID(st.PersonID).Name1);
ltrlSpeakers.Text = string.Join(", ", personNames);
尝试使用LINQ:
string result = string.Join(",",
(from t in sessionTeachers select EMS.PWDAL.DALHelper.GetPersonByID(t.PersonID).Name1))
使用内置字符串。
ltrlSpeakers.Text = string.Join(
", ",
sessionTeachers.Select(z => z.EMS.PWDAL.DALHelper.GetPersonByID(z.PersonID).Name1);
试一下:
ltrlSpeakers.Text =
String.Join(", ",
sessionTeachers
.Select(teacher => EMS.PWDAL.DALHelper.GetPersonByID(teacher.PersonID).Name1)
.ToArray()
);
最好的办法是
ltrlSpeakers.Text =
String.Join(", ",
sessionTeachers
.Select(teacher => EMS.PWDAL.DALHelper.GetPersonByID(teacher.PersonID).Name1)
.ToArray()
);
ltrlSpeakers.Text = ltrlSpeakers.Text.trimend(',')