On Wed, 01 Oct 2008 10:32:25 -0700, CSharper <cs******@gmx.comwrote:
[...]
I have two questions here;
Is it possible to include all these && conditions in the Lambda
(stupid question) since most of all the examples I have seen are one
liners.
Sure. The lambda expression can be arbitrarily complex:
s =s.Attributes().Count() 0 && s.Attribute("id") != null &&
s.Attribute("id").Value.Equals("1")
You can even use braces and declare local variables for efficiency (though
this particular example is probably contrived, since the extra lookup of
the attribute may not be that expensive):
s ={ Attribute attr; return s.Attributes().Count() 0 && (attr =
s.Attribute("id")) != null && attr.Value.Equals("1"); }
Also what is the difference between the lambda and linq in
this selection that doesn't return the value?
That I'm not sure about. I would expect an exception to occur when you
don't check for null, but it would surprise me that the Where() method
would eat the exception. But then, maybe it does and if so maybe that's
by design. I don't know enough about it.
One side note, which is
the good way to code, lambda or linq? I see the benefits of linq but
for an untrained eye lambda could be confusing.
That's three questions. :p
I think the phrase "lambda or LINQ" is ill-conceived. The two are not
mutually exclusive, and you are using LINQ in either example. In the
first example, you're using the LINQ methods directly, while in the
second, you're using the new C# LINQ syntax to automatically generate code
to call the LINQ methods.
But, if you're asking whether one syntax or the other is preferred of the
two examples you provided, I'd say that's mostly a matter of preference,
and partly a matter of utility. In particular, for the most part it's
just what you think reads better, but I've run into situations where the
compiler can't do delegate type inference unless you're using the methods
directly, so in those cases it might make more sense to use the explicit
LINQ methods rather than reworking whatever lambda expression one has to
get the implicit LINQ syntax to work.
Pete