locked
Replacing foreach with Linq RRS feed

  • Question

  • Is it possible to replace the foreach loop in the following code with Linq?

    Car car = new Car();
    List<string> carNames=new List<string>();
    CarDetailsServiceResponse response = xxxx;
    foreach(Car c in response.CarDetails)
    {
       car.carName = c.Name;
       carNames.Add(car.carName);
    }

     

     

    Wednesday, January 19, 2011 8:11 PM

Answers

  • You could change this to:

    CarDetailsServiceResponse response = xxxx;
    List<string> carNames = response.CarDetails.Select(c => c.Name).ToList();
    
    


    Reed Copsey, Jr. - http://reedcopsey.com
    If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".
    • Proposed as answer by RoninB Wednesday, January 19, 2011 8:49 PM
    • Marked as answer by sireesha yetchina Wednesday, January 19, 2011 9:19 PM
    Wednesday, January 19, 2011 8:33 PM
    Moderator

All replies

  • You could change this to:

    CarDetailsServiceResponse response = xxxx;
    List<string> carNames = response.CarDetails.Select(c => c.Name).ToList();
    
    


    Reed Copsey, Jr. - http://reedcopsey.com
    If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".
    • Proposed as answer by RoninB Wednesday, January 19, 2011 8:49 PM
    • Marked as answer by sireesha yetchina Wednesday, January 19, 2011 9:19 PM
    Wednesday, January 19, 2011 8:33 PM
    Moderator
  • Thank you Reed! This is what I was looking for..Its concise and more effective!
    Wednesday, January 19, 2011 9:21 PM