T3db0t
T3db0t

Reputation: 3551

C# - Error CS1928: Checking for list element with derived class

I have custom class deriving from a library (Satsuma) like so:

public class DCBaseNode : Node {
    public bool selected = false;
}

and a Neighbors method in the library that returns List<Node>. I want to be able to do this:

graph.Neighbors(theNode).Any(n => n.selected == true);

But Any sees n as a Node, not DCBaseNode, so it doesn't understand .selected.

So I tried:

graph.Neighbors(theNode).Any<DCBaseNode>(n => n.selected == true);

...which gives me this error:

Error CS1928: Type System.Collections.Generic.List<Satsuma.Node>' does not contain a memberAny' and the best extension method overload `System.Linq.Enumerable.Any(this System.Collections.Generic.IEnumerable, System.Func)' has some invalid arguments

...but I'm not clear on how the arguments are invalid.

Upvotes: 6

Views: 206

Answers (1)

Jim Bolla
Jim Bolla

Reputation: 8295

Sounds like you need to downcast...

graph.Neighbors(theNode)
    .OfType<DCBaseNode>()
    .Any(n => n.selected);

Upvotes: 6

Related Questions