Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

linq

generics

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.

like image 593
T3db0t Avatar asked Aug 13 '14 19:08

T3db0t


1 Answers

Sounds like you need to downcast...

graph.Neighbors(theNode)
    .OfType<DCBaseNode>()
    .Any(n => n.selected);
like image 101
Jim Bolla Avatar answered Sep 21 '22 15:09

Jim Bolla