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

RJP*_*RJP 3 c# linq-to-xml

我有这个代码:

   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
        }
Run Code Online (Sandbox Code Playgroud)

其结果是varIEnumerable<MyObject>,我需要使用foreach循环分配xObj:

foreach(var i in x)
{
    Obj = i;
}
Run Code Online (Sandbox Code Playgroud)

有没有办法可以使用LINQ语句而没有IEnumerable以这种方式返回?或者foreach像我一样使用循环是否正常?

Jes*_*cer 6

是的:

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();
Run Code Online (Sandbox Code Playgroud)