views:

120

answers:

3

The return type of my query is IEnumerable<XElement>. how can i convert the resultant data to XElement type? is it possible? could some body help me to understand this.

var resQ = from e in docElmnt.Descendants(xmlns + Constants.T_ROOT)
                             .Where(x => x.Attribute(Constants.T_ID).Value == "testid") 
           select e;

I have to pass resQ as a parameter to the below fuction. in order to do that i have to convert resQ to XElement type.

Database.usp_InsertTestNQuestions(tid, qId, qstn, ans, resQ ); 

Thanks in advance Madhu

+3  A: 

As long as your query only returns a single result, you can either call Single() or First() on the result (also, there's no need for the extra query syntax up top):

// Use if there should be only one value.
// Will throw an Exception if there are no results or more than one.
var resQ = docElmnt.Descendents(xmlns + Constants.T_ROOT)
                   .Single(x => x.Attribute(Constants.T_ID).Value == "testid");

// Use if there could be more than one result and you want the first.
// Will throw an Exception if there are no results.
var resQ = docElmnt.Descendents(xmlns + Contants.T_ROOT)
                   .First(x => x.Attribute(Constants.T_ID).Value == "testid");

If you want to handle the case when no results are returned for the query without throwing an Exception, you can use SingleOrDefault (which will still throw an Exception if you get more than one result) or FirstOrDefault.

Justin Niessner
Note that `First()` can be called without generating exceptions if the collection returns *more* than one element.
kbrimington
That worked like charm. Thanks Justin
BumbleBee
A: 

You can iterate over each element in the query and then call the method with your enumerator.

resQ.ToList().ForEach( e=> ...func... );

asawyer
A: 

In addition to Justin's answer, you may want to allow for 0 elements returned or some other condition.

In that case, simply do a:

IEnumerable<XElement> resQ = docElmnt.Descendents(xmlns + Constants.T_ROOT)
                   .Where(x => x.Attribute(Constants.T_ID).Value == "testid");
if(resQ.Count() == 0) {
  //handle no elements returned
} else if(resQ.Count() > 1) {
  //handle more than 1 elements returned
} else {
  XElement single = resQ.Single();
}

Most of the time I find it's best not to throw an error-- unless having exactly 1 returned is really important.

smdrager
I read somewhere that .Any() is better to use then .Count() ... may have been on Eric Lippert's blog.
asawyer