我有这个代码:
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)
其结果是var是IEnumerable<MyObject>,我需要使用foreach循环分配x到Obj:
foreach(var i in x)
{
Obj = i;
}
Run Code Online (Sandbox Code Playgroud)
有没有办法可以使用LINQ语句而没有IEnumerable以这种方式返回?或者foreach像我一样使用循环是否正常?
是的:
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)