Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Casting the Foreach value to one of it's properties

Tags:

c#

oop

foreach

I'm not sure that title conveys my meaning, please change it if you can better define this question in a sentence.

I'd like to iterate through a collection of T, but instead of working with the (T)object, I want to retrieve (T)object.SomeProperty.

How I can do it:

List<Car> _cars;
FillList(_cars);

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

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

What I'd love to do:

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 lazier programmer?

like image 287
Michael Avatar asked Jun 22 '12 14:06

Michael


2 Answers

You can use LINQ and select:

foreach (Windshield ws in _cars.Select(car => car.Windshield))
{
    ws.DoWorkA();
    ws.DoWorkB();
    ws.DoWorkC();
}
like image 169
nemesv Avatar answered Oct 17 '22 21:10

nemesv


use Linq:

List<Car> _cars; 
FillList(_cars);  
foreach (Windshield ws in _cars.Select(c=>c.Windshield) {
         ws.DoWorkA();
         ws.DoWorkB();
         ws.DoWorkC(); 
    } 
like image 1
D Stanley Avatar answered Oct 17 '22 20:10

D Stanley