A Problem about Collections

zystein

New member
Joined
Nov 29, 2022
Messages
3
Programming Experience
Beginner
Screenshot 2022-11-29 115306.png


I identified 2 collections. Their names are numbers1 and numbers2. I identified another collection called common. After, I added number1 and number2 to common collection. The problem is that I delete item 4 in collection called common but I also want to delete item 4 in collection called numbers. According to codes on image 4 is deleted only from common collection. How can I fix that problem? Is there any short way to make this? I can fix that using if else but it last too long. I hope you understand my problem. Sorry for my English.
 
Last edited by a moderator:
C#:
            List<int> numbers1 = new List<int>() { 2, 3, 4, 5, 6 };
            List<int> numbers2 = new List<int>() { 7, 8, 9 };
            List<int> common = new List<int>();
            common.AddRange(numbers1);
            common.AddRange(numbers2);
            foreach (var item in common)
            {
                Console.WriteLine(item);
            }

            common.Remove(4);
 
As for your question, there's really no way to do that. The lists themselves are totally independent so modifying one can and will have no effect on another. You have no choice but to remove the item from the original lists yourself as well. You could build some data structure that had references to all three lists and you could tell it to remove the item, but then it would have to do multiple separate removals.

You could create your own collection class where the combined list did have knowledge of the lists from which it was comprised and could do the child removals but, again, there'd still have to be code in it to do the removals from the child lists.
 
It doesn't have to be an algorithm. It could be a data structure with an list like interface as described above.

Imagine something like this:
C#:
class UncommonList<T> : IList<T>
{
    List<List<T>> _lists = new List<List<T>>();

    public void AddRange(List<T> list) => _lists.Add(list);

    public bool Remove(T item)
    {
        bool removed = false;
        foreach(var list in _lists)
            removed |= list.Remove(item);
        return removed;
    }

    public int Count => _lists.Aggregate(0, (count, list) => count + list.Count);
:
}
 
While eating a quick lunch, I realized that Remove() above could be written as:
C#:
public bool Remove(T item) => _lists.Aggregate(false, (removed, list) => list.Remove(item) | removed);

Anyway, as pointed out by @jmcilhinney , doing things this way is not the expected behavior for the way lists normally work in the .NET world. Proceed with caution should you decide to implement a list like this.
 
Back
Top Bottom