C# AnonymousType中的Perserving数组

C# AnonymousType中的Perserving数组,c#,linq-to-xml,anonymous-types,C#,Linq To Xml,Anonymous Types,我在网上找了一些参考资料,但运气不太好。希望这只是我忽略的一些简单的事情,但是在我的代码中,我在参与者列表中循环,并将查询结果存储到数组中。正如您所知,我的foreach语句将只添加数组的最后一个元素,因为第一个元素已被替换 如何将值添加到下一个数组索引中。因此,如果数组中有[2],如何确保this.physentityphysicallftEntityId包含[2],而不是始终包含[1]?如果我需要澄清,请告诉我 if (leftParticipants.Length >= 0) //

我在网上找了一些参考资料,但运气不太好。希望这只是我忽略的一些简单的事情,但是在我的代码中,我在参与者列表中循环,并将查询结果存储到数组中。正如您所知,我的foreach语句将只添加数组的最后一个元素,因为第一个元素已被替换

如何将值添加到下一个数组索引中。因此,如果数组中有[2],如何确保this.physentityphysicallftEntityId包含[2],而不是始终包含[1]?如果我需要澄清,请告诉我

if (leftParticipants.Length >= 0) // Check to see if LeftParticipants exists
{
   for (int c = 0; c < leftParticipants.Length; c++)
   {
       var l_entityIDs = 
          from BioList in o_data.Descendants(bp + "physicalEntityParticipant")
          where BioList.Attribute(rdf + "ID").Value == leftParticipants[c].TrimStart('#')
          select new
          {
              o_entityIDs = BioList.Elements(bp + "PHYSICAL-ENTITY")
              .Select(entityID => entityID.Attribute(rdf + "resource").Value).ToArray()
          };

       foreach (var entity in l_entityIDs)
       {
           this.physEntityPhysicalLeftEntityIDs = entity.o_entityIDs;  // Set SmallMolecules from Left
       }
    }
}

如果你想把它当作一个数组/列表,你所要做的就是

l_enityIDs.ToList

然后.Addnew{o_entityIDs=foo}

如果要将其添加到IEnumerable,则需要一个扩展方法返回源enumberable中的所有内容,并在下一个值上添加一个yield语句。

如果PhysentityPhysicallFTEntityId是一个数组,则需要初始化一个索引变量,并通过foreach循环每次递增该变量:

这假设您已经在数组中分配了足够的空间。如果数组中包含的项太多,则会出现索引越界错误

为了确保数组中有足够的空间,您可以在上面的循环之前分配它:

this.physEntityPhysicalLeftEntityIds = new int[l_entityIDs.Count()];

将该行中的int替换为正确的类型。您没有说明数组中存储的是什么类型。

PhysentityPhysicalFTEntityId的类型是什么?您的问题是如何用匿名类型的实例填充数组?我不确定问题到底是什么。@JaredPar PhysistentityPhysicalFTEntityId的类型是String[],我应该包括它,抱歉。好提示!类型为字符串[]。。。我想你是指新的int[l_entityid.Count];
this.physEntityPhysicalLeftEntityIds = new int[l_entityIDs.Count()];