Showing posts with label ArrayList. Show all posts
Showing posts with label ArrayList. Show all posts

Monday, January 27, 2014

How to loop through a collection that supports IEnumerable?

Whenever you get to this issue, though it seems a really easy job to do here 2 ways how you can iterate on a collection that supports IEnumerable:

First one using a foreach statement:

foreach (var item in collection)
{
    // play with your item
}

I suggest that always when you know your object types of collection to use that type instead of var. I always try to avoid var type. It is something that my team lead advised me and I came to realize it is a good practice.

Then second way to do it is using for statement. Whenever you have a collection and you need to iterate it and according to some conditions some elements might have to be removed you cannot use foreach because you will have a nice error saying: "Collection was modified; enumeration operation may not execute" :) So that is why you need to use for statement.

for(int i = 0; i < collection.Count(); i++) 
{
    string str1 = collection.ElementAt(i);
    // play with your item
}

There might be other ways to iterate, like using GetEnumerator but is enough, for the moment :)
Have a nice day.

Monday, January 9, 2012

How to substract 2 ArrayLists in C#?

Well the answer might be really easy for some of you but for newbies is not.
So considering that we have 2 arraylists.
 
ArrayList FirstArray = new ArrayList(new[] { "23", "25", "27" });
ArrayList SecondArray = new ArrayList(new[] { "25", "28", "29" });


and we want the difference.For that this is what you have to do. Call a method that I implemented.
 
ArrayList Difference = Substract2ArrayLists(FirstArray, SecondArray, true);
Method:
 
    /// 
    /// Substracts 2 array lists/a difference
    /// 
    /// 

First ArrayList
    /// 

Second ArrayList
    /// 

True if compare string, False for long values
    /// 
    static public ArrayList Substract2ArrayLists(ArrayList First, ArrayList Second, bool IsString)
    {
        if (IsString)
        {
            foreach (string secondValue in Second)
            {
                First.Remove(secondValue);
            }
        }
        else
        {
            foreach (long secondValue in Second)
            {
                First.Remove(secondValue);
            }
        }
        return First;
    }