从匿名类型保留数组

时间:2009-03-23 03:59:23

标签: c# linq-to-xml anonymous-types

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

如何将值添加到下一个数组索引中。那么,如果数组中有[2],我怎样才能确保this.physEntityPhysicalLeftEntityID包含[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
       }
    }
}

2 个答案:

答案 0 :(得分:1)

如果您想将它视为数组/列表,那么您只需要

l_enityIDs.ToList()

然后.Add(new {o_entityIDs = foo})

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

答案 1 :(得分:1)

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

int destIndex = 0;       
foreach (var entity in l_entityIDs)
{
    this.physEntityPhysicalLeftEntityIDs[destIndex] = entity.o_entityIDs;  // Set SmallMolecules from Left
    ++destIndex;
}

假设您已在阵列中分配了足够的空间。如果项目中的项目数量超过了数组,那么您将获得超出范围的索引错误。

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

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

用适当的类型替换该行中的int(您没有说明数组中存储的类型)。