Convert IEnumerable <XElement> to XElement

The return type of my request IEnumerable<XElement>. How can I convert the resulting data to a type XElement? Is it possible? can any body help me figure this out.

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

I need to pass resQ as a parameter to the following function. for this i need to convert resQ to type XElement.

Database.usp_InsertTestNQuestions(tid, qId, qstn, ans, resQ ); 
+3
source share
3 answers

As long as your query returns only one result, you can either call Single () or First () as a result (there is also no need for an additional query syntax up):

// 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");

, , SingleOrDefault ( - , ) FirstOrDefault.

+7

, .

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

In addition to Justin's answer, you can allow the return of 0 elements or another condition.

In this case, just do:

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

In most cases, I think it’s better not to throw an error - unless 1 has definitely been returned.

+1
source

Source: https://habr.com/ru/post/1761974/


All Articles