3

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:

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? Or is it normal to use a foreach loop the way I am?


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();
4

3 回答 3

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();
于 2012-05-03T21:48:22.997 回答
1

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

于 2012-05-03T21:50:24.527 回答
1

You need to retrieve the first item. I would personally create this after your LINQ query:

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.

于 2012-05-03T21:53:00.730 回答