将字符串添加到列表 - 更快捷的方法?

时间:2013-05-30 02:43:31

标签: c# string list add

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

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
}

3 个答案:

答案 0 :(得分:6)

var apptList = appointments.Select(a => a.Subject).ToList();

答案 1 :(得分:2)

我不确定我的代码是否正确,但由于你的Appointment类已经实现了IEnumerable,你应该可以调用ToList()将它一次性转换为一个列表。

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

答案 2 :(得分:1)

这个怎么样:

List<string> apptList = appointments.Select(x => x.Subject).ToList();