PutraKg
PutraKg

Reputation: 2246

Cast object type in a LINQ statement

I have a Layer collection which contains a Content object as a property. How do I cast this Content to its original object to get its property in LINQ statement?

For example:

var item = Layers.FirstOfDefault(x =>(PushPin)x.Content.Description == "xyz");

In this case Content is of PushPin object type and I want to compare its Description property to xyz

Upvotes: 3

Views: 7992

Answers (4)

latonz
latonz

Reputation: 1750

If all content objects in Layers are PushPin objects this should be ok for you:

var item = Layers.Select(x => x.Content).Cast<PushPin>().FirstOrDefault(x => x.Description == "xyz");

But this will throw an InvalidCastException if there are objects in Layers which cannot be casted to PushPin. If Layers contains different object-types but you only need the PushPins, OfType should work:

var item = Layers.Select(x => x.Content).OfType<PushPin>().FirstOrDefault(x => x.Description == "xyz");

Upvotes: 1

Ruben
Ruben

Reputation: 6427

When Content can be something other then PushPin

var item = Layers.Select(x => x.Content).OfType<PushPin>().FirstOfDefault(c => c.Description == "xyz");

or when all Content are PushPin's

var item = Layers.Select(x => x.Content).Cast<PushPin>().FirstOfDefault(c => c.Description == "xyz");

i.e. the first one will filter the PushPin types, the second one will cast all Content to PushPin.

Upvotes: 1

Rob Epstein
Rob Epstein

Reputation: 1500

If Content can be something other than PushPin then you will need something along the lines of

var item = Layers.FirstOrDefault(x => x.Content is PushPin && ((PushPin)x.Content).Description == "xyz");

Upvotes: 6

Selman Gen&#231;
Selman Gen&#231;

Reputation: 101681

Enclose it with parentheses

var item = Layers.FirstOfDefault(x => ((PushPin)x.Content).Description == "xyz");

Upvotes: 5

Related Questions