c# - IEnumerable 集合中元素的序号位置 (Linq to XMl )

标签 c# linq linqdatasource

如何在此 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,


                                        }   
                                         )


                      };

最佳答案

您无法轻松地使用查询表达式来完成此操作 - 至少会产生可怕的副作用。但是,您可以使用 SelectWhere 的点表示法轻松完成此操作。鉴于您有一个相当长的查询表达式,最简单的方法可能是在开头嵌入一个额外的调用 - 假设您确实想要原始表达式中的“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/

相关文章:

asp.net - 如何在asp.net中修改Bind ("MyValue")

dynamic-data - ASP.NET 动态数据向页面添加其他筛选条件

c# - 如何使用 config c# 中的规则在 NLog 中发送特定功能

c# - 我在构建 Linq 查询时做错了什么

c# - C#中var的初始化

c# - 在运行时在 EF6 扩展 DbContext 类中创建 JOIN

c# - 检查 dataGridView 是否在其任何单元格上设置了 errorText

c# - 如何从字符串 C# 中找到连字符的位置剥离字符串

c# - 如何将所有对象从一个 IList 移动/复制到另一个