将子项添加到循环中的类属性

时间:2014-05-26 15:17:44

标签: c# for-loop

我在从AddressElement对象添加子元素时遇到问题

我的测试班:

    public class AddressElement
    {
       public AddressElement[] AddressElement1 { get; set; }
       public string PostIndex { get; set; }

    }

我的测试界面:

    public interface IAddress
    {
      string PostIndex { get; }
    }

    private AddressElement CreateAddressElement(IAddress address)
            {
                return new AddressElement
                {                
                    PostIndex = address.PostIndex                
                };
            }

    private int startIndex = 0;
    private int finalIndex = 5;

获取元素方法:

private AddressElement [] GetAddressElements(List addresses,int startIndex,int finalIndex)     {           列表addressElements = new List();

for (int i = startIndex; i < finalIndex; i++)
            {
if (i == startIndex)
                {
 addressElements.Add(CreateAddressElement(addresses[i]));

if (i != startIndex )
                {
 AddressElement addressElement = addressElements[startIndex];
addressElements[startIndex].AddressElement1 = new[] { CreateAddressElement(addresses[i]) };    

}

    I need add all subelements of AddressElement in for cycle: addressElements[startIndex].AddressElement1[startIndex].AddressElement1[startIndex].AddressElement1[startIndex].AddressElement1[startIndex]....

1 个答案:

答案 0 :(得分:0)

您可以使用Linq:

来完成此操作
private AddressElement[] GetAddressElements(List addresses, int startIndex, int finalIndex) {

  return addresses.Skip(startIndex).Take(finalIndex - startIndex).Select(s => CreateAddressElement(s)).ToArray() ; 
}

希望它会对你有所帮助。