Click here to Skip to main content
Sign Up to vote bad
good
See more: C#4.0
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 27 Jan '13 - 19:58


2 solutions

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
  Permalink  
// 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
  Permalink  
Comments
Member 8233601 - 28 Jan '13 - 6:37
my arraylist is populated at the runtime...
Member 8233601 - 28 Jan '13 - 6:42
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)

  Print Answers RSS
Your Filters
Interested
Ignored
     
0 Sergey Alexandrovich Kryukov 428
1 OriginalGriff 318
2 Mayur_Panchal 148
3 Mohammed Hameed 145
4 Dave Kreskowiak 120
0 Sergey Alexandrovich Kryukov 8,123
1 OriginalGriff 6,173
2 CPallini 3,482
3 Rohan Leuva 2,703
4 Maciej Los 2,234


Advertise | Privacy | Mobile
Web03 | 2.6.130516.1 | Last Updated 28 Jan 2013
Copyright © CodeProject, 1999-2013
All Rights Reserved. Terms of Use
Layout: fixed | fluid