是否有更快或更有效的方法将字符串添加到列表而不是以下示例?:
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
}
答案 0 :(得分:6)
var apptList = appointments.Select(a => a.Subject).ToList();
答案 1 :(得分:2)
我不确定我的代码是否正确,但由于你的Appointment类已经实现了IEnumerable,你应该可以调用ToList()将它一次性转换为一个列表。
答案 2 :(得分:1)
这个怎么样:
List<string> apptList = appointments.Select(x => x.Subject).ToList();