I got this code printing all the IDs with latest timestamp. But i would like to remove the elements who isnt the latest timestamp and then save as XML file. There is plenty more attributes then ID and timestamp so i would like to remove those who isnt latest timestamp.
static void Main(string[] args)
{
XElement xelement = XElement.Load("data.xml");
var employees = xelement.Elements()
.Select(e => new
{
Name = e.Element("Employee").Value,
ChangeTimeStamp = DateTime.Parse(e.Element("ChangeTimeStamp").Value)
})
.GroupBy(e => e.Name)
.Select(g => new
{
Name = g.Key,
ChangeTimeStamp = g.Max(e => e.ChangeTimeStamp)
});
foreach (var employee in employees)
{
Console.WriteLine("{0} {1}", employee.Name, employee.ChangeTimeStamp);
}
Console.ReadKey();
}
}
I would like to create xml file with all unique IDs with latest timestamp and all other attributes.
public static void Main(string[] args)
{
var xelement = XElement.Load("data.xml");
var employees = xelement.Elements()
.Select(e => new
{
Element = e,
Name = e.Element("Employee").Value,
ChangeTimeStamp = DateTime.Parse(e.Element("ChangeTimeStamp").Value)
})
.GroupBy(e => e.Name)
.Select(g =>
{
var maxTimestamp = g.Max(e => e.ChangeTimeStamp);
foreach (var e in g)
{
if (e.ChangeTimeStamp < maxTimestamp)
{
e.Element.Remove();
}
}
return new
{
Name = g.Key,
ChangeTimeStamp = maxTimestamp
};
});
xelement.Save(yourPathToSave);
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments