开发者

Linq Query ToList not putting data into a list, but rather a one element list

I have the following query (which is nested in a larger query):

PaymentType = (from paymenttype in offer.Elements(myns + "paymentTypes")
               select paymenttype.Value).ToList()

myns is an XNamespace type

the XML tree looks like

<offer>
    <paymentTypes>
        <paymentType>One String</paymentType>
        <paymentType>Another string</paymentTYpe>
    </paymentTypes>
</offer>

PaymentType is defined as:

L开发者_开发知识库ist<string> PaymentType = new List<string>();

When my code executes, what I am seeing is a single item created:

PaymentType[0] = "OneStringAnotherString"

and not

PaymentType[0] = "OneString"
PaymentType[1] = "AnotherString"

I can't sort out what I am doing wrong. Any ideas?


If you look at it in the debugger, it's easier to tell that what you're getting back is the paymentTypes element. If you know there's only one, the simplest change is to add .Elements() onto the end to get the children:

        var results = (from paymenttype in offer.Elements("paymentTypes").Elements()
                       select paymenttype.Value).ToList();

That gets you the 2 strings you were looking for.


The Value of <paymentTypes> in your example is "One StringAnother string".

You need to select the Value from each <paymentType> individually:

var query = from paymenttype in offer.Element(myns + "paymentTypes")
                                     .Elements(myns + "paymentType")
            select paymenttype.Value;

List<string> PaymentType = query.ToList();

Or, if there are multiple <paymentTypes>, the Value from each <paymentType> in each <paymentTypes>:

var query = from paymenttypes in offer.Elements(myns + "paymentTypes")
            from paymenttype in paymenttypes.Elements(myns + "paymentType")
            select paymenttype.Value;

List<string> PaymentType = query.ToList();


This will find all paymentType elements

var paymentTypes = (from paymentType 
                    in offer.Descendants(myns + "paymentType") 
                    select paymentType.Value).ToList();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜