Accessing a field of a class after a lambda expression
I have a weighted graph with its nodes and edges.
Each node contains a LinkedList called edges that stores the edges of this node. Each edge has an weight and a node (node at the other end).
I already did this:
static void removeEdge(Node n1, Node n2)
{
n1.edges.Remove(n1.edges.First(a => a.node == n2));
n2.edges.Remove(n2.edges.First(a => a.node == n1));
}
I am trying to do an updateEdge method, that would take that same lambda expression and then do this:
(a => a.node == n2).weight = otherValue;
but I am getting an error. Isn't this allowed? Or am I doing something wrong? From what I've tested the lambda expression seems ok as far as removing the elements, though I'm new at this so I'm pretty lost 开发者_如何学Ctbh.
I think you're misunderstanding what a lambda is. When you say something like
...First(x => x.bar == 10)
what happens is we generate something like this:
static bool M(X x) { return x.bar == 10; }
...
... First(new Func<X, bool>( M ) )
That is, we make a method out of the lambda, and then make a delegate out of the method, and then pass the delegate.
Doing something like
(x=>x.bar==10).foo = whatever
is morally the same as doing something like M.foo = whatever, where M is a method. Methods don't have properties, so this is always illegal. Similarly, lambdas don't have properties either. A lambda is just a convenient syntax for a method.
Oooooooh!
I just needed to do this:
n1.edges.First(a => a.node == n2).weight = otherValue;
n2.edges.First(a => a.node == n1).weight = otherValue;
精彩评论