Click here to Skip to main content
15,893,337 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,
I am stuck with a problem pls try to solve. In my project i have to arraylist whose size may or may be not same. I want to add elements of the two arraylist i.e arr1[0]+arr2[0],arr1[1]+arr2[1].
My problem is if the size of two arraylist is different then how it add the elements which is out of index i.e if arr1 has three elements and arr2 has four elements then upto third element of arr1 and arr2 it works fine but at the fourth index of arr1 which does not exist is shows error....
thanks
Posted

int length1 = arr1.Count;
int length2 = arr2.Count;
int minLength= (length1<length2)?length1:length2;
int maxLength= (length1>length2)?length1:length2;
Console.WriteLine("The Resulted Array List Are:");
for(int i=0; i < minLength; i++)
{
Console.WriteLine(Convert.ToInt32(arr1[i])+Convert.ToInt32(arr2[i]));
}

if (minLength != maxLength)
{
if (arr1.Count == maxLength)
{
int i = minLength;
while (i != maxLength)
{
Console.WriteLine(Convert.ToInt32(arr1[i]));
i++;
}
}

if (arr2.Count == maxLength)
{
int i = minLength;
while (i != maxLength)
{
Console.WriteLine(Convert.ToInt32(arr2[i]));
i++;
}
}
}
Console.ReadLine();

Note: ArrayList is Object so dont forget to convert into respective type
 
Share this answer
 
// declare first array list and two items
ArrayList list = new ArrayList();
// you can add your list dynamically here it is manualy added for demo purpuse
list.Add(1);
list.Add(2);
// // declare 2nd array list and 4 items
ArrayList list2 = new ArrayList();
list2.Add(1);
list2.Add(2);
list2.Add(3);
list2.Add(4);
//if codition
if (list.Count > list2.Count)
{
for (int i = 0; i < list2.Count; i++)
{
Response.Write((int)list[i]+(int)list2[i]);
}
}
else if (list2.Count > list.Count)
{
for (int i = 0; i < list.Count; i++)
{
Response.Write((int)list[i] + (int)list2[i]);
}
}
//Note: Edit List items to see the effect
 
Share this answer
 
v2
Comments
Member 8233601 28-Jan-13 6:37am    
my arraylist is populated at the runtime...
Member 8233601 28-Jan-13 6:42am    
ok leave i solve this problem
can u tell how to make string like this 20,30,40 from arr[20,30,40] i.e my arraylist contain 3 or 4 elements and i want to make sting out of it. I try it like this
foreach(string h in arr)
{
labl += h+",";
}
it come out with result like this 20,30,40,

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900