Panagiotis Kanellopoulos Panagiotis Kanellopoulos - 1 month ago 8
C# Question

c# Access ObservableCollection as base

I have a class with base an Observable collection. I am trying to set the Observablecollection from a List of items with the method clone as shown below:

public class MyObservableCollection : ObservableCollection<Record>
{
public void Clone(List<Record> originalEnityList)
{
ObservableCollection<Record> cloned = new ObservableCollection<Record>(originalEnityList);
}
}


What i would like to do is to copy the cloned collection to the base ObservableCollection like:

this= new ObservableCollection<Record>(originalEnityList);
or
this=cloned;


How can i do that?

I have tried the following without any progress:


  1. ObservableCollection mine = this; mine=cloned;(While the mine collection is set the base collection remains empty).

  2. I tried to do this from outside the class with no luck also, like
    MyObservableCollection coll = new ObservableCollection<Record>(originalEnityList);
    But i believe that MyObervableCollection is missing the new constructor that observablecollection has.



PS: I haved tried to use foreach and for to populate the collection but because my collection is really big, it takes too much time.

I am pretty sure that i am missing something really simple here.

Answer

You could simply add a constructor that takes the source collection as parameter:

public class MyObservableCollection : ObservableCollection<Record> 
{
    public MyObservableCollection()
    {
    }

    public MyObservableCollection(List<Record> originalEntityList)
        : base(originalEntityList)
    {
    }
}

With a static Clone methold like

private static List<Record> Clone(List<Record> originalEntityList)
{
    return ...
}

you could write the second constructor like this:

public MyObservableCollection(List<Record> originalEntityList)
    : base(Clone(originalEntityList))
{
}
Comments