473,795 Members | 2,805 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

linq vs lambda

I have following XML
<root>
<Person id="1">
<Name>a</Name>
</Person>
<Person id="2">
<Name>b</Name>
</Person>
</root>

I am trying to find the person with id = 1 and I use the following

var people =
doc.Decendents( ).Elements("Per son").Where(s=> s.Attribute("id ").Value.Equals ("1"));

When I run I get an empty list but when I change this to pure linq

var people = from c in doc.Decendents( ).Elements("Per son")
where c.Attributes(). Count() 0
&& c.Attribute("id ") != null
&& c.Attribute("id ").Value.Equals ("1")
select c;

This one does return me the first note.

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. Also what is the difference between the lambda and linq in
this selection that doesn't return the value? 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.

Thanks.
Oct 1 '08 #1
4 5099
On Wed, 01 Oct 2008 10:32:25 -0700, CSharper <cs******@gmx.c omwrote:
[...]
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.Equa ls("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
Oct 1 '08 #2
On Oct 1, 1:08*pm, "Peter Duniho" <NpOeStPe...@nn owslpianmk.com>
wrote:
On Wed, 01 Oct 2008 10:32:25 -0700, CSharper <cshar...@gmx.c omwrote:
[...]
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.Equa ls("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
Hi Pete,

Thank you for the answer (I sneaked third question in and you cought
me on that). By any chance why the first query doesn't return the
value while the second one does?

Thanks.
Oct 1 '08 #3
On Wed, 01 Oct 2008 11:21:01 -0700, CSharper <cs******@gmx.c omwrote:
Thank you for the answer (I sneaked third question in and you cought
me on that). By any chance why the first query doesn't return the
value while the second one does?
You had three questions. I had three answers. It looks like you skipped
over one. :)
Oct 1 '08 #4
On Oct 1, 12:32 pm, CSharper <cshar...@gmx.c omwrote:
I have following XML
<root>
<Person id="1">
<Name>a</Name>
</Person>
<Person id="2">
<Name>b</Name>
</Person>
</root>

I am trying to find the person with id = 1 and I use the following

var people =
doc.Decendents( ).Elements("Per son").Where(s=> s.Attribute("id ").Value.Equals ("1"));

When I run I get an empty list but when I change this to pure linq

var people = from c in doc.Decendents( ).Elements("Per son")
where c.Attributes(). Count() 0
&& c.Attribute("id ") != null
&& c.Attribute("id ").Value.Equals ("1")
select c;

This one does return me the first note.

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. Also what is the difference between the lambda and linq in
this selection that doesn't return the value? 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.

Thanks.
That can't be your actual code, because there is no method called
"Decendents " in the XDocument class. That must be a typo.

In any event, I ran the following code:

static void Main(string[] args) {

var xml = new XElement("root" ,
new XElement("Perso n",
new XAttribute("id" , "1"),
new XElement("Name" , "a")),
new XElement("Perso n",
new XAttribute("id" , "2"),
new XElement("Name" , "b")));

XDocument doc = new XDocument();
doc.Add(xml);

var people1 = doc.Descendants ().Elements("Pe rson").Where(s
=s.Attribute("i d").Value.Equal s("1"));

foreach (XElement element in people1) {
Console.WriteLi ne(element.ToSt ring());
}

Console.WriteLi ne();

var people2 = from c in
doc.Descendants ().Elements("Pe rson")
where c.Attributes(). Count() 0
&& c.Attribute("id ") != null
&& c.Attribute("id ").Value.Equals ("1")
select c;

foreach (XElement element in people2) {
Console.WriteLi ne(element.ToSt ring());
}

Console.WriteLi ne();

Console.WriteLi ne("Press ENTER to exit");
Console.ReadLin e();
}
With the following results:

<Person id="1">
<Name>a</Name>
</Person>

<Person id="1">
<Name>a</Name>
</Person>

Press ENTER to exit

So it appears to work correctly to me. Either you've got a typo
somewhere in your code or your xml does not match what you are showing
us.

Can you supply a small, but complete code example that duplicates the
problem?

Chris

Chris
Oct 1 '08 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
1397
by: Scott Nonnenberg [MSFT] | last post by:
LINQ and C# 3.0 "Couldn't attend PDC but still want to talk to the C# team? This chat is your chance! Join the C# team to discuss the .NET Language Integrated Query Framework (LINQ) and newly announced C# 3.0 features like extension methods, lambda expressions, type inference, and anonymous types. You've read some of the documentation, maybe played around with the preview - now talk to members of the team!" Now this is some exciting...
14
21779
by: Ralf Rottmann \(www.24100.net\) | last post by:
I recently stumbled across a pretty interesting LINQ to SQL question and wonder, whether anybody might have an answer. (I'm doing quite some increasing LINQ evangelism down here in Germany.). Assume I want to select rows from a database and check whether a specific column contains keywords from a list of keywords. The following works just fine: List<stringsearchTerms = new List<string>() { "Maria", "Pedro" };
22
10382
by: paululvinius | last post by:
Hi! Testing som Linq-expressions and tried to measure performance and compare it to pre-Linq programming. The folloing two methods are functional equal but the non-Linq one is twice as fast. public List<ConferenceRoomOldWay(int minimumSeatingCapacity) {
8
46887
by: Andy | last post by:
Hi, I'm trying to add a where clause to my query: List<stringtypes = new List<string>(); types.Add( "A" ); types.Add( "B" ); query = query.Where( c =types.Contains( c.Type ) );
1
1868
by: shapper | last post by:
Hi, I wonder, is there some tool that transforms SQL procedures to LINQ? :-) I want to use LINQ but I have so much work done in SQL that would be great to transform my SQL code to LINQ. Thanks, Miguel
21
4368
by: hrishy | last post by:
Hi Will LINQ be ported to Python ? regards Hrishy
3
221
by: Marc Gravell | last post by:
A lambda expression is a short form to write a delegate In /this/ case (LINQ-to-Objects): yes - but it could equally be compiled to an Expression, which is very, very different. A lambda *statement*, on the other hand, is always a delegate. Marc
2
3534
by: Colin Han | last post by:
Hi, all, If I write follow code in c# method. The IDE will compile it to a complex construct method of System.Linq.Expression. Expression<Func<int>ex = () =10; will be compile to: Expression<Func<int>ex = Expression.Lambda<Func<int>(Expression.Literal(10)) It is so smart. I can travel in this expression tree. I can do some smart abilities on this design. Now, I want write a console application. If user input follow string from console,...
5
3884
by: Edwin | last post by:
I am trying to write an application among which one of the functions is to determine the number of unique extensions found in a directory and all of its sub directories. I am trying to use Linq to XML to do this. Below is the code being used to accomplish what I am trying to do. In the "if" statement, I am trying to update the <Count></CountElement to "TESTING". However what I will really want is to add 1 to the existing numerical...
0
9673
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9522
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10443
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10002
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7543
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6783
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5437
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4113
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3728
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.