1

I'm looking a way to insert arraylist in two different arraylist with same number of items. for an example:

I have ArrayList something like this

ArrayList mainArrayList = new ArrayList {1, 2, 3,4,5,6};

So what I want from mainArrayList to insert into two arraylist (arraylist1 and arraylist 2)

this is what i am looking to have in two arraylist:

ArrayList arrayList1 = new ArrayList {1, 2, 3};
ArrayList arrayList2 = new ArrayList {4, 5, 6};

I can do through for loop but i am sure there is better of doing this.

 for (int i = 0; i < mainArrayList.Count; i++)
 {
    if(arraylist1.Count <3) {
       arrayList1.Add(mainArrayList[i]);
    }
    if(arrayList1.Count >3)
    {
       arrayList2.Add(mainArrayList[i]);
    }
}
2
  • 1
    First, don't use ArrayList, use List<T>, where T is the type to store (in this case int.) Once you do that, you can use the LINQ Concat() method to get what you want: mainList = firstList.Concat(secondList).ToList(); Commented May 4, 2013 at 0:11
  • i updated my question... i think you got confused with my question. so what i am looking is from mainlist data i want two arraylist or list with equal data on in it in my case firstlist 1,2,3 and in secondlist 4,5,6 - hope i make sense. Commented May 4, 2013 at 0:19

2 Answers 2

2

Use List<T> instead of ArrayList which is an old non-generic container. Then you can use GetRange():

List<int> mainList = new List<int> {1, 2, 3, 4, 5, 6};

List<int> list1 = mainList.GetRange(0, 3);
List<int> list2 = mainList.GetRange(3, 3);
Sign up to request clarification or add additional context in comments.

Comments

1

Use GetRange(from, length)

ArrayList mainArrayList = new ArrayList { 1, 2, 3, 4, 5, 6 };

ArrayList arrayList1 = mainArrayList.GetRange(0, 3);
ArrayList arrayList2 = mainArrayList.GetRange(3, 3);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.