cc81
cc81

Reputation: 23

Strange result with string comparison in LINQ

I have a XML source with nodes like this (Somewhat anonymized):

<XXX>
        <Code A="oa  ">01</Code>
        <Name A="oa  ">Card</Name>
        <F1 A="oa  ">x</F1>
        <F2 A="oa  ">y</F2>
        <F3 A="oa  ">z</F3>
</XXX>

I load the XML-document into a XElement and query it with linq

var query = from creditcard in xml.Descendants("XXX")
                    where creditcard.Element("Code").Value == "1"
                    select new
                    {
                        Id = Convert.ToInt32(creditcard.Element("Code").Value),
                        Description = creditcard.Element("Name").Value,
                        xx = creditcard.Element("F1").Value,
                        yy = creditcard.Element("F2").Value,
                        zz = creditcard.Element("F3").Value
                    };

This will result in a empty set when I dump the query in LinqPad. However if I change the where clause to:

where Convert.ToInt32(creditcard.Element("Code").Value) == 1

Then it will correctly find the item in question. Any ideas why it works this way or what I have missed?

EDIT: Sorry, I missed to change a "Kod" to Code as I changed it for posting. Fixed now.

Upvotes: 0

Views: 124

Answers (3)

AxelEckenberger
AxelEckenberger

Reputation: 16926

The query does not work as you will have to process siblings not child elements.

Your query works for:

<XXX>
    <Code>
        <Kod A="oa  ">01</Kod>
        <Name A="oa  ">Card</Name>
        <F1 A="oa  ">x</F1>
        <F2 A="oa  ">y</F2>
        <F3 A="oa  ">z</F3>
    </Code >
</XXX>

But even then only if you modify

where creditcard.Element("Code").Value == "1"

to

where creditcard.Element("Code").Element("Kod").Value == "01"

Upvotes: 0

Shimrod
Shimrod

Reputation: 3205

As your first comparaison is made on string, you try to compare "01" with "1", which is obviously not the same. By converting "01" to an integer value, you get an int with a value = 1, so your comparaison is right this time.

Upvotes: 0

Matthew Flaschen
Matthew Flaschen

Reputation: 284836

Because the value is "01", not "1". Converting to Int32 masks this difference.

Upvotes: 4

Related Questions