如何在此 linq 查询中嵌入元素的序号作为其属性。
var AllSections = from s in xmlDoc.Descendants("section")
select new
{
id = s.Attribute("id").Value,
themeTitle = s.Element("themeTitle").Value,
themeText = s.Element("themeText").Value,
objects = (from a in AllObjects
join b in s.Descendants("object")
on a.Attribute("accessionNumber").Value equals
b.Attribute("accessionNumber").Value
//select a
select new
{
//index = insert ordinal id/index of element
ObjectTitle = a.Element("ObjectTitle").Value,
ObjectText = a.Element("textentry").Value,
}
)
};
最佳答案
您无法轻松地使用查询表达式来完成此操作 - 至少会产生可怕的副作用。但是,您可以使用 Select
或 Where
的点表示法轻松完成此操作。鉴于您有一个相当长的查询表达式,最简单的方法可能是在开头嵌入一个额外的调用 - 假设您确实想要原始表达式中的“s”索引:
var AllSections =
from s in xmlDoc.Descendants("section")
select new
{
id = s.Attribute("id").Value,
themeTitle = s.Element("themeTitle").Value,
themeText = s.Element("themeText").Value,
objects = (from a in AllObjects.Select((Item,Index) => new {Item,Index})
join b in s.Item.Descendants("object")
on a.Item.Attribute("accessionNumber").Value equals
b.Attribute("accessionNumber").Value
//select a
select new
{
//index = insert ordinal id/index of element
Index = a.Index,
ObjectTitle = a.Element("ObjectTitle").Value,
ObjectText = a.Element("textentry").Value,
}
)
};
假设您需要 AllObjects
中的 a
索引。
关于c# - IEnumerable 集合中元素的序号位置 (Linq to XMl ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1400806/