C # Listing a Foreach value for one of its properties

I am not sure if the name conveys my meaning, please change it if you can better define this issue in the sentence.

I would like to iterate through the T collection, but instead of working with the (T) object, I want to get the T.SomeProperty object.

How can i do this:

List<Car> _cars;
FillList(_cars);

foreach (Car car in _cars)
{
    Windshield ws = car.Windshield;

    ws.DoWorkA();
    ws.DoWorkB();
    ws.DoWorkC();
}

What I will do with pleasure:

List<Car> _cars;
FillList(_cars);

foreach (Car car in _cars using ws as Windshield = car.Windshield)
{
    ws.DoWorkA();
    ws.DoWorkB();
    ws.DoWorkC();
}

Any way to become an even more lazy programmer?

+5
source share
2 answers

You can use LINQ and choose:

foreach (Windshield ws in _cars.Select(car => car.Windshield))
{
    ws.DoWorkA();
    ws.DoWorkB();
    ws.DoWorkC();
}
+14
source

use linq:

List<Car> _cars; 
FillList(_cars);  
foreach (Windshield ws in _cars.Select(c=>c.Windshield) {
         ws.DoWorkA();
         ws.DoWorkB();
         ws.DoWorkC(); 
    } 
+1
source

All Articles