Linq Query ToList不将数据放入列表,而是放入一个元素列表

时间:2010-11-24 04:32:56

标签: c# linq-to-xml

我有以下查询(嵌套在更大的查询中):

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

myns是一个XNamespace类型

XML树看起来像

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

PaymentType定义为:

List<string> PaymentType = new List<string>();

当我的代码执行时,我看到的是创建的单个项目:

PaymentType[0] = "OneStringAnotherString"

而不是

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

我无法理清我做错了什么。有什么想法吗?

3 个答案:

答案 0 :(得分:1)

您示例中的Value <paymentTypes>"One StringAnother string"

您需要从每个Value单独选择<paymentType>

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

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

或者,如果有多个<paymentTypes>,则Value中每个<paymentType>的{​​{1}}:

<paymentTypes>

答案 1 :(得分:1)

如果你在调试器中查看它,就会更容易分辨出你收到的是paymentTypes元素。如果你知道只有一个,那么最简单的改变就是在末尾添加.Elements()以获得孩子:

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

这会让你获得你想要的2个字符串。

答案 2 :(得分:0)

这将找到所有paymentType元素

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