sgowd
sgowd

Reputation: 1034

How to use list.where function with the objects getting casted before getting an IEnumerable

My classes are like this

public interface ICar
{
    CarModel GetCarModel();
}

public class Honda: ICar
{
    CarModel GetCarModel()
    {
        return CarModel.Honda;
    }
}

I have a list of ICars defined like this:

List<ICar> cars;

I am looking to extract a IEnumerable of all cars of type Honda using the Where clause and casted to Honda and not to ICar. How do I do this? Is this possible?

Upvotes: 2

Views: 282

Answers (3)

Moradnejad
Moradnejad

Reputation: 3663

You can do it, by something like this:

IEnumerable<ICar> results = cars.Where(s => s.GetCarModel == CarModel.Honda);
var hondas = results.Select(c => (Honda)c);

Upvotes: 1

Richard Schneider
Richard Schneider

Reputation: 35477

var result = cars.OfType<Honda>();

See the docs

Upvotes: 6

Zohar Peled
Zohar Peled

Reputation: 82474

Where only returns a filtered IEnumerable. You need to use Select also:

var listOfHonda = cars.Where(c => c.GetCarModel() == CarModel.Honda).Select(c => (Honda)c);

Upvotes: 2

Related Questions