locked
How to remove the objects from one Arralist to another arraylist and create new array. RRS feed

  • Question

  • Hi all,

    I want to know how to create a new Array list which remove the objects an array list to another array list.

    For Example

    Arraylist1 is having 10 objects.

    Arraylist2 is having 3 objects.

    Arraylist3 is Arraylist1-Arraylist2 is equal to 7 objects.

    is it possible to do this way or is there any other way?

    Thanks in advance any one to assist me.

    Thanks

    Anilkumar

    Thursday, March 7, 2019 5:23 AM

Answers

  • Hi Anilkumar.Renila,

    Thank you for posting here.

    For your question, you want to create a new Array list which remove the objects an array list to another array list.

    You could try the following code.

    static void Main(string[] args)
            {
                ArrayList list1 = new ArrayList();
                list1.Add("test1");
                list1.Add("test2");
                list1.Add("test3");
                list1.Add("test4");
                list1.Add("test5");
                list1.Add("test6");
                list1.Add("test7");
                list1.Add("test8");
                list1.Add("test9");
                list1.Add("test10");
                ArrayList list2 = new ArrayList();
                list2.Add("test1");
                list2.Add("test2");
                list2.Add("test3");
                ArrayList list3 = new ArrayList();
               var result = list1.ToArray().Except(list2.ToArray()).ToArray();
                foreach (var item in result)
                {
                    list3.Add(item);
                }
                foreach (var item in list3)
                {
                    Console.WriteLine(item);
                }
            }

    Result:

    Best regards,

    Jack


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Friday, March 8, 2019 5:18 AM
    Moderator

All replies

  • Hi all,

    I want to know how to create a new Array list which remove the objects an array list to another array list.

    For Example

    Arraylist1 is having 10 objects.

    Arraylist2 is having 3 objects.

    Arraylist3 is Arraylist1-Arraylist2 is equal to 7 objects.

    is it possible to do this way or is there any other way?

    Thanks in advance any one to assist me.

    Thanks

    Anilkumar

    >> I want to know how to create a new Array list which remove the objects...

    That's impossible! An ArrayList does not remove objects from anywhere. It's your code which does it (if you program to do it).

    >> How to remove the objects from one Arralist to another arraylist and create new array.

    First of all, you must understand that an ArrayList may hold items of different types.

    What I understand by your title, is: you want to move all items in ArrayList1, which differs from all items in ArrayList2, to a new ArrayList3.

    As you see, from the underlined text above, the solution is very simple.

    You have to find all items in ArrayList1 that are different from all items in ArrayList2, and "move" them to ArrayList3

    You have to compose the "move" by 2 ops: delete from one ArrayList and add to another ArrayList.



    • Edited by ritehere44 Thursday, March 7, 2019 5:58 AM missing word
    Thursday, March 7, 2019 5:55 AM
  • Remember that, in C#, there's no real penalty in having an object in multiple arrays.  The array just contains a reference to the object, not the whole object.  Thus, you don't have to worry very much about "moving" the objects.  You can run a loop through the original arraylist, and sort the items into the other two arraylists, then delete the original arraylist.

    Tim Roberts | Driver MVP Emeritus | Providenza & Boekelheide, Inc.

    Thursday, March 7, 2019 6:42 AM
  • Thanks for your reply.

    What you understood is correct. I need to find and remove/Delete “Arraylist2” objects from “Arraylist1”, and create new array list for balance objects in “ArrayList1”.

    Can you give me any sample code.

    Thanks

    Anilkumar


    Thursday, March 7, 2019 6:49 AM
  • Deleting the ArrayList will also delete those items that do not meet the criteria to be "moved". So, its necessary (I guess) to delete one by one in the process (and, at the same time, adding to the other ArrayList).

    If, at the end of the process, the ArrayList becomes empty, then the OP will, probably, want to delete it too.

    The solution is very simple, as to the reasoning, but the code is long.

    Thursday, March 7, 2019 6:56 AM
  • ArrayList is an old school collection. Please don't use it in current code. Use List<T> or Collection<T> or equivalent instead. If you're using one of them then the extension method Intersect can be used to find all values in both collections. However if you're working with some old code then ArrayList may still be used.

    I think people are getting wrapped around your terminology a little bit so let's clarify that you aren't actually interested in updating either Arraylist1 or Arraylist2, you just want the dups in a third list right?

    Step 1 would be to get the data consistent. ArrayList is just a glorified list of objects. In most cases people store the same types in the ArrayList but the compile won't enforce this. Review the code that is inserting items into your ArrayLists. If they are always the same type then you can convert them to IEnumerable<T> where T is the common type.

    var typedList1 = Arraylist1.OfType<MyData>();
    var typedList2 = Arraylist1.OfType<MyData>();

    Here `MyData` is the type that you're storing in the ArrayLists. If there is no one type that is being inserted then you aren't going to be able to do much with the list at all but you could still use `OfType` on `Object`. It just doesn't do much.

    Now that you have the ArrayLists converted to IEnumerable<T> you can now use LINQ to get to the rest of the stuff you want. You want to use `Intersect` to get all the items that are in both lists. The problem is that it uses equality comparison (as does almost everything else). For primitives it just works but for a custom type you have to define "equality" yourself.

    //Sample type of what you might be storing in your ArrayLists
    class MyData
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
    
    //Simple comparer that just compares Id of the data
    class MyDataEqualityComparer : IEqualityComparer<MyData>
    {
        public bool Equals ( MyData x, MyData y ) { return x?.Id == y?.Id; }
    
        public int GetHashCode ( MyData obj ) { return obj.Id.GetHashCode(); }
    }

    Your comparer can be as simple or complex as you need but note that Intersect relies on GetHashCode so you need to ensure any objects that are "equal" return the same hash code.

    With this infrastructure in place you can now get the differences.

    var list1 = new ArrayList() {
        new MyData() { Id = 1, Name = "Bob" },
        new MyData() { Id = 2, Name = "Sue" },
        new MyData() { Id = 3, Name = "Jan" },
        new MyData() { Id = 4, Name = "Mark" },
    };
    var list2 = new ArrayList() {
        new MyData() { Id = 2, Name = "Sue" },
        new MyData() { Id = 4, Name = "Mark" },
        new MyData() { Id = 5, Name = "Joe" },
        new MyData() { Id = 6, Name = "Karen" },
    };
    
    //All the same type so switch to IEnumerable<MyData> instead
    var typedList1 = list1.OfType<MyData>();
    var typedList2 = list2.OfType<MyData>();
    
    var comparer = new MyDataEqualityComparer();
    var diffs = typedList1.Intersect(typedList2, comparer);
    
    //Need an ArrayList?
    var diffList = new ArrayList(diffs.ToList());
    Again, if you cannot identify a shared type that all elements in the ArrayList have then you're stuck using `Object`. When it comes to the call to `Intersect` you won't be able to define a reasonable comparer so you'll get the intersection of all items that are the same object in both lists.


    Michael Taylor http://www.michaeltaylorp3.net

    Thursday, March 7, 2019 3:35 PM
    Moderator
  • ArrayList is an old school collection. Please don't use it in current code. Use List<T> or Collection<T> or equivalent instead. If you're using one of them then the extension method Intersect can be used to find all values in both collections. However if you're working with some old code then ArrayList may still be used.

    I think people are getting wrapped around your terminology a little bit so let's clarify that you aren't actually interested in updating either Arraylist1 or Arraylist2, you just want the dups in a third list right?

    Step 1 would be to get the data consistent. ArrayList is just a glorified list of objects. In most cases people store the same types in the ArrayList but the compile won't enforce this. Review the code that is inserting items into your ArrayLists. If they are always the same type then you can convert them to IEnumerable<T> where T is the common type.

    var typedList1 = Arraylist1.OfType<MyData>();
    var typedList2 = Arraylist1.OfType<MyData>();

    Here `MyData` is the type that you're storing in the ArrayLists. If there is no one type that is being inserted then you aren't going to be able to do much with the list at all but you could still use `OfType` on `Object`. It just doesn't do much.

    Now that you have the ArrayLists converted to IEnumerable<T> you can now use LINQ to get to the rest of the stuff you want. You want to use `Intersect` to get all the items that are in both lists. The problem is that it uses equality comparison (as does almost everything else). For primitives it just works but for a custom type you have to define "equality" yourself.

    //Sample type of what you might be storing in your ArrayLists
    class MyData
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
    
    //Simple comparer that just compares Id of the data
    class MyDataEqualityComparer : IEqualityComparer<MyData>
    {
        public bool Equals ( MyData x, MyData y ) { return x?.Id == y?.Id; }
    
        public int GetHashCode ( MyData obj ) { return obj.Id.GetHashCode(); }
    }

    Your comparer can be as simple or complex as you need but note that Intersect relies on GetHashCode so you need to ensure any objects that are "equal" return the same hash code.

    With this infrastructure in place you can now get the differences.

    var list1 = new ArrayList() {
        new MyData() { Id = 1, Name = "Bob" },
        new MyData() { Id = 2, Name = "Sue" },
        new MyData() { Id = 3, Name = "Jan" },
        new MyData() { Id = 4, Name = "Mark" },
    };
    var list2 = new ArrayList() {
        new MyData() { Id = 2, Name = "Sue" },
        new MyData() { Id = 4, Name = "Mark" },
        new MyData() { Id = 5, Name = "Joe" },
        new MyData() { Id = 6, Name = "Karen" },
    };
    
    //All the same type so switch to IEnumerable<MyData> instead
    var typedList1 = list1.OfType<MyData>();
    var typedList2 = list2.OfType<MyData>();
    
    var comparer = new MyDataEqualityComparer();
    var diffs = typedList1.Intersect(typedList2, comparer);
    
    //Need an ArrayList?
    var diffList = new ArrayList(diffs.ToList());
    Again, if you cannot identify a shared type that all elements in the ArrayList have then you're stuck using `Object`. When it comes to the call to `Intersect` you won't be able to define a reasonable comparer so you'll get the intersection of all items that are the same object in both lists.


    Michael Taylor 

    Ex mvp and still moderator Michael.

    I see some concepts and your code expose talent of a newbie in programming, so, some fixes and comments are necessary:

    (it follows)

    Friday, March 8, 2019 3:24 AM
  • First

    ...you have to define "equality" yourself.
    class MyDataEqualityComparer : IEqualityComparer<mydata>
    Michael Taylor </mydata>

    You shouldn't suggest the implementation of IEqualityComparer<>, because it is old-very-old school.
    Instead, derive your type from EqualityComparer<>.
    This is up to date school.

    Second

    var typedList1 = Arraylist1.OfType<mydata>();
    Michael Taylor </mydata>

    Notice, the OP has an ArrayList, therefore, you should consider many more types:
    var typedList2 = Arraylist2.OfType<string>();
    var typedList3 = Arraylist3.OfType<int>();
    var typedList4 = Arraylist4.OfType<List<string>>();
    var typedList5 = Arraylist5.OfType<List<int>>();
    var typedList6 = Arraylist6.OfType<StringBuilder>();
    etc...

    Third

    Intersect relies on GetHashCode
    Michael Taylor

    No, Intersect() does not rely on GetHashCode(), the way you say.
    To prove you're wrong, make the GetHashCode() implementation return any constant value, and your code (posted) will behave the same.
    Your original code (posted) outputs Sue and Mark (which is wrong); after you make the change just mentioned, the output will be exactly the same.
    Conclusion:
    Intersect() relies on Equals() and GetHashCode().

    Fourth

    var diffs = typedList1.Intersect(typedList2, comparer);
    var diffList = new ArrayList(diffs.ToList());
    Michael Taylor

    You are trying to determine differences (var diffs and var diffList) with Intersect()!
    This is impossible!
    The code you posted, outputs Sue and Mark, which are common to both collections.
    The OP is, clearly, wanting to determine the difference.

    Fifth

    @Michael Taylor

    The OP, clearly says, wants to "move" specific objects from ArrayList1 to ArrayList3(!), and you are not doing this.

    Sixth

    @Michael Taylor

    Notice, your code is old-styled, so, I'm gonna suggest you start to read and understand anonymous types!
    They are very useful!
    I suggest you use this code below, instead of your long and outdated code:

    // IEqualityComparer<> and EqualityComparer<> are unnecessary
    
    typedList1
        .Select(t=>new{Id=t.Id,Name=t.Name})
        .Intersect(
            typedList2.Select(t=>new{Id=t.Id,Name=t.Name})
        )
        .ToList()
        .ForEach(t=>Console.WriteLine("{0} {1}",t.Id,t.Name))
        ;

    My very much simpler code above, outputs the same values as yours: Sue and Mark (but the OP wants the opposite).

    P.S.: there'll be a test on Monday on anonymous types and my smart code above.

    Friday, March 8, 2019 3:27 AM
  • Hi Anilkumar.Renila,

    Thank you for posting here.

    For your question, you want to create a new Array list which remove the objects an array list to another array list.

    You could try the following code.

    static void Main(string[] args)
            {
                ArrayList list1 = new ArrayList();
                list1.Add("test1");
                list1.Add("test2");
                list1.Add("test3");
                list1.Add("test4");
                list1.Add("test5");
                list1.Add("test6");
                list1.Add("test7");
                list1.Add("test8");
                list1.Add("test9");
                list1.Add("test10");
                ArrayList list2 = new ArrayList();
                list2.Add("test1");
                list2.Add("test2");
                list2.Add("test3");
                ArrayList list3 = new ArrayList();
               var result = list1.ToArray().Except(list2.ToArray()).ToArray();
                foreach (var item in result)
                {
                    list3.Add(item);
                }
                foreach (var item in list3)
                {
                    Console.WriteLine(item);
                }
            }

    Result:

    Best regards,

    Jack


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Friday, March 8, 2019 5:18 AM
    Moderator
  • > I see some concepts and your code expose talent of a newbie in programming

    Don't be an asshole, especially to people who are helping others for free.


    Tim Roberts | Driver MVP Emeritus | Providenza &amp; Boekelheide, Inc.

    Friday, March 8, 2019 5:25 AM

  • Don't be an asshole, especially to people who are helping others for free.


    Tim Roberts

    Someone who post a mix of wrong/old-styled/logically-incorrect code, CAN'T HELP people who are TRYING TO LEARN, IDIOT.

    Moreover, the only asshole I seeing here, it's THE BIG ONE right below your stinking NOSE!

    Saturday, March 9, 2019 3:59 AM