是否可以将此 foreach 循环转换为 LINQ-to-XML 循环?
Is it possible to convert this foreach loop into a LINQ-to-XML loop?
我最初问过这个问题 (Can we automatically add a child element to an XElement in a sortable manner?) and it was closed as a duplicate (how to add XElement in specific location in XML Document)。
这是我目前拥有的代码:
bool bInserted = false;
foreach (var weekDB in xdoc.Root.Elements())
{
DateTime datWeekDB = DateTime.ParseExact(weekDB.Name.LocalName, "WyyyyMMdd", CultureInfo.InvariantCulture);
if (datWeekDB != null && datWeekDB.Date > historyWeek.Week.Date)
{
// Insert here
weekDB.AddBeforeSelf(xmlHistoryWeek);
bInserted = true;
break;
}
}
if (!bInserted)
xdoc.Root.Add(xmlHistoryWeek);
它工作正常。但我想知道我是否可以使用 LINQ 来实现同样的目的?链接的答案表明:
Search element you want to add and use Add method as shown below
xDoc.Element("content")
.Elements("item")
.Where(item => item.Attribute("id").Value == "2").FirstOrDefault()
.AddAfterSelf(new XElement("item", "C", new XAttribute("id", "3")));
但我不明白如何根据我的代码逻辑得出这样的逻辑。
我认为最好的思考方式是:您将使用 LINQ 来查找特定元素。然后你将根据你找到的内容插入到文档中。
所以像这样:
var targetElement = xdoc.Root.Elements()
.Where(weekDB => {
DateTime datWeekDB = DateTime.ParseExact(weekDB.Name.LocalName, "WyyyyMMdd", CultureInfo.InvariantCulture);
return datWeekDB != null && datWeekDB.Date > historyWeek.Week.Date;
})
.FirstOrDefault();
if (targetElement == null)
{
xdoc.Root.Add(xmlHistoryWeek);
}
else
{
targetElement.AddBeforeSelf(xmlHistoryWeek);
}
我最初问过这个问题 (Can we automatically add a child element to an XElement in a sortable manner?) and it was closed as a duplicate (how to add XElement in specific location in XML Document)。
这是我目前拥有的代码:
bool bInserted = false;
foreach (var weekDB in xdoc.Root.Elements())
{
DateTime datWeekDB = DateTime.ParseExact(weekDB.Name.LocalName, "WyyyyMMdd", CultureInfo.InvariantCulture);
if (datWeekDB != null && datWeekDB.Date > historyWeek.Week.Date)
{
// Insert here
weekDB.AddBeforeSelf(xmlHistoryWeek);
bInserted = true;
break;
}
}
if (!bInserted)
xdoc.Root.Add(xmlHistoryWeek);
它工作正常。但我想知道我是否可以使用 LINQ 来实现同样的目的?链接的答案表明:
Search element you want to add and use Add method as shown below
xDoc.Element("content") .Elements("item") .Where(item => item.Attribute("id").Value == "2").FirstOrDefault() .AddAfterSelf(new XElement("item", "C", new XAttribute("id", "3")));
但我不明白如何根据我的代码逻辑得出这样的逻辑。
我认为最好的思考方式是:您将使用 LINQ 来查找特定元素。然后你将根据你找到的内容插入到文档中。
所以像这样:
var targetElement = xdoc.Root.Elements()
.Where(weekDB => {
DateTime datWeekDB = DateTime.ParseExact(weekDB.Name.LocalName, "WyyyyMMdd", CultureInfo.InvariantCulture);
return datWeekDB != null && datWeekDB.Date > historyWeek.Week.Date;
})
.FirstOrDefault();
if (targetElement == null)
{
xdoc.Root.Add(xmlHistoryWeek);
}
else
{
targetElement.AddBeforeSelf(xmlHistoryWeek);
}