Manual iteration on selecting XML elements (C #, XDocument)

What is the “best practice” way of manually repeating (that is, one at a time with the “next” button) over the XElements set in my XDocument? Let's say I select the set of elements I want:

var elems = from XElement el in m_xDoc.Descendants()
            where (el.Name.LocalName.ToString() == "q_a") 
            select el;

I can use IEnumerator to iterate over them, i.e. IEnumerator m_iter;

But when I get to the end, and I want to wrap it at the beginning, if I call Reset () on it, it throws a NotSupportedException. This is because the Microsoft C # 2.0 specification in Chapter 22, Iterators, says, "Note that enumerator objects do not support the IEnumerator.Reset method. Calling this method throws a System.NotSupportedException".

So what is the right way to do this? And what if I also want to have bidirectional iteration, i.e. The back button, too?

Someone at the Microsoft discussion forum said that I should not use IEnumerable directly. He said that there is a way to do what I want with LINQ, but I did not understand that. Someone else suggested dropping XElements into a list with ToList (), which I think would work, but I was not sure if this is "best practice." Thanks in advance for any suggestions!

+3
source share
2 answers

The solution is very simple. Just create a List from your XElements collection.

var elems = (from XElement el in m_xDoc.Descendants()
            where (el.Name.LocalName.ToString() == "q_a") 
            select el).ToList();

elems[i] . / ( ).

xml, , linq (. MSDN Linq XML). IEnumerable.Reset(), . .ToList<T>(), - .

+1

; foreach elems. :

// first time
foreach(var item in elems) {...}
// second time
foreach(var item in elems) {...}

Reset() - GetEnumerator() , . - , , - , ToList().

+1

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


All Articles