3

是否有比以下示例更快或更有效的方式将字符串添加到列表中?:

List<String> apptList = new List<String>();

foreach (Appointment appointment in appointments){

    String subject = appointment.Subject;
    //...(continues for another 10 lines)

    //...And then manually adding each String to the List:   
    apptList.Add(subject);
    //...(continues for another 10 lines)

    //And then send off List apptList to another method
}
4

3 回答 3

6
var apptList = appointments.Select(a => a.Subject).ToList();
于 2013-05-30T02:45:49.027 回答
2

我不确定我的代码是否正确,但是由于您的 Appointment 类已经实现了 IEnumerable,因此您应该能够调用 ToList() 将其一次性转换为列表。

http://msdn.microsoft.com/en-us/library/bb342261.aspx

于 2013-05-30T02:46:22.457 回答
1

这个怎么样:

List<string> apptList = appointments.Select(x => x.Subject).ToList();
于 2013-05-30T02:49:05.537 回答