简体   繁体   English

LINQ to XML返回一个对象而不是IEnumerable <object>

[英]LINQ to XML return an object instead of IEnumerable<object>

I have this code: 我有这个代码:

   MyObject Obj {get;set;}
    var x = from xml in xmlDocument.Descendants("Master")
        select new MyObject
        {
            PropOne = //code to get data from xml
            PropTwo = //code to get data from xml
        }

The result is var being IEnumerable<MyObject> , and I need to use a foreach loop to assign x to Obj : 结果是varIEnumerable<MyObject> ,我需要使用foreach循环将x分配给Obj

foreach(var i in x)
{
    Obj = i;
}

Is there a way I can use a LINQ statement and not have an IEnumerable returned in that way? 有没有办法可以使用LINQ语句而没有以这种方式返回IEnumerable Or is it normal to use a foreach loop the way I am? 或者像我一样使用foreach循环是否正常?

Yep: 是的:

Obj = (from xml in xmlDocument.Descendants("Master")
        select new MyObject
        {
            PropOne = //code to get data from xml
            PropTwo = //code to get data from xml
        }).FirstOrDefault();

If you're only returning one object, you can do this: 如果您只返回一个对象,则可以执行以下操作:

 MyObject Obj {get;set;}

 var x = (from xml in xmlDocument.Descendants("Master")
    select new MyObject
    {
        PropOne = //code to get data from xml
        PropTwo = //code to get data from xml
    }).Single();

Now your x object should be of type MyObject 现在你的x对象应该是MyObject类型

You need to retrieve the first item. 您需要检索第一个项目。 I would personally create this after your LINQ query: 我会在你的LINQ查询之后亲自创建它:

var element = xmlDocument.Descendants("Master").Single(); // Or .First() if appropriate
Obj = new MyObject
    {
        PropOne = //code to get data from xml in "element"
        PropTwo = //code to get data from xml in "element"
    };

I personally find this more clearly matches your intent, as you're retrieving the single element, then building a single object from it. 我个人发现这更符合您的意图,因为您正在检索单个元素,然后从中构建单个对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM