I am using the follow Code to read an XML file:
XDocument doc = XDocument.Load(xmlPath);
foreach (var node in doc.Descendants("LogInfo"))
{
ListViewItem item = new ListViewItem(new string[]
{
node.Element("MailBox").Value,
node.Element("LastRun").Value,
});
listViewHome.Items.Add(item);
}
How can I change this Code to receive just the last "n" number of elements from that XML file? Thanks in advance.
You could do this:
var nodes = doc.Descendants("LogInfo");
foreach (var node in nodes.Skip(Items.Count() - n))
{
...
}
Or this:
var nodes = doc.Descendants("LogInfo");
foreach (var node in nodes.Reverse().Take(n).Reverse())
{
...
}
If you're feeling adventurous, you could also write your own extension method which should be more efficient than either of these. Here's my quick and dirty solution:
public static IEnumerable<T> TakeFromEnd<T>(this IEnumerable<T> items, int n)
{
var arry = new T[n];
int i = 0;
foreach(var x in items)
{
arry[i++ % n] = x;
}
if (i < n)
{
n = i;
i = 0;
}
for (int j = 0; j < n; j++)
{
yield return arry[(i + j) % n];
}
}
var nodes = doc.Descendants("LogInfo");
foreach (var node in nodes.TakeFromEnd(n))
{
...
}
XDocument doc = XDocument.Load(xmlPath);
var logs = doc.Descendants("LogInfo");
var logsCount = logs.Count();
foreach (var node in logs.Skip(logsCount - n).Take(n))
{
ListViewItem item = new ListViewItem(new string[]
{
node.Element("MailBox").Value,
node.Element("LastRun").Value,
});
listViewHome.Items.Add(item);
}
And here is XPath solution, which will enumerate xml once
var xpath = String.Format("//LogInfo[position()>last()-{0}]", n);
foreach (var log in doc.XPathSelectElements(xpath))
{
ListViewItem item = new ListViewItem(new string[]
{
(string)log.Element("MailBox"),
(string)log.Element("LastRun")
});
listViewHome.Items.Add(item);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.