2
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);

它工作正常,但有没有更好更有效的简单方法?

4

5 回答 5

3

像这样的东西:

var personNames = sessionTeachers.Select(
      st => EMS.PWDAL.DALHelper.GetPersonByID(st.PersonID).Name1);
ltrlSpeakers.Text = string.Join(", ", personNames);
于 2013-03-01T12:38:10.273 回答
3

尝试使用 LINQ:

string result = string.Join(",",
(from t in sessionTeachers select EMS.PWDAL.DALHelper.GetPersonByID(t.PersonID).Name1))
于 2013-03-01T12:39:02.083 回答
1

请改用内置的String.Join方法。

ltrlSpeakers.Text = string.Join(
    ", ", 
    sessionTeachers.Select(z => z.EMS.PWDAL.DALHelper.GetPersonByID(z.PersonID).Name1);
于 2013-03-01T12:37:19.807 回答
1

试试这样:

        ltrlSpeakers.Text = 
        String.Join(", ",
            sessionTeachers
                .Select(teacher => EMS.PWDAL.DALHelper.GetPersonByID(teacher.PersonID).Name1)
                .ToArray()
        );
于 2013-03-01T12:40:51.540 回答
0

最好的方法是 ltrlSpeakers.Text = String.Join(", ", sessionTeachers .Select(teacher => EMS.PWDAL.DALHelper.GetPersonByID(teacher.PersonID).Name1) .ToArray() ); ltrlSpeakers.Text = ltrlSpeakers.Text.trimend(',')

于 2013-03-01T13:02:25.200 回答