Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding String to a List - Quicker way?

Is there a quicker or more efficient way to add Strings to a List than the below example?:

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
}
like image 631
LKB Avatar asked Jan 28 '26 02:01

LKB


2 Answers

var apptList = appointments.Select(a => a.Subject).ToList();
like image 132
Keith Nicholas Avatar answered Jan 30 '26 14:01

Keith Nicholas


I'm not sure if I'm getting your code right, but since your Appointment class is already implementing IEnumerable, you should be able to call ToList() to convert it to a list in one shot.

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

like image 34
user2434792 Avatar answered Jan 30 '26 14:01

user2434792



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!