Chris Halcrow
Chris Halcrow

Reputation: 31940

C# linq query to filter out only items of a specified type, that meet a specified condition

I have a collection that can contain different types. If the object is of type 'A', I just want to return that object, however if the object is of type 'B', then I want to return it only if it meets a certain condition (the condition will be invalid for type A and so will throw an exception if I try to check it). Something like:

model.MyList = model.MyList.Where(d => d.GetType().Equals(typeof(MyTypeB)) ? !d.IsSomeCondition: d );

Upvotes: 0

Views: 352

Answers (2)

Slai
Slai

Reputation: 22876

Something like this:

.Where(d => d is MyTypeA || (d is MyTypeB && !(d as MyTypeB).IsSomeCondition)));

Upvotes: 1

Keith Nicholas
Keith Nicholas

Reputation: 44288

just return true

d => d.GetType().Equals(typeof(MyTypeB)) ? !d.IsSomeCondition: true

where is just filtering so only needs a true or false response.

Upvotes: 1

Related Questions