Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting an array to an ObservableCollection

In a C# application the following array is used:

CProject[] projectArray = this.proxy.getProjectList(username, password);

However I need the projectArray as a ObservableCollection<CProject>. What would be the recommended way to do this? So far I'm using the following statement:

ObservableCollection<CProject> projectList = new ObservableCollection<CProject>(projectArray);

Would you also use this statement or would you recommend other ways?

like image 967
Robert Strauch Avatar asked Mar 08 '13 09:03

Robert Strauch


2 Answers

Building a new collection from an IEnumerable as you did is the way to do it.

like image 116
ken2k Avatar answered Nov 06 '22 00:11

ken2k


IMHO , Building a new collection each time you want to add range of objects is not good rather i would follow below design.

Build a class inheriting from ObservableCollection , so that you can access Items property which is protected and then create a AddRange Method which will add items into it

public class MyObObservableCollection<T> : ObservableCollection<T>
{
    public void AddRange(IEnumerable<T> items)
    {
        foreach (var item in items)
        {
            this.Items.Add(item);
        }

    }
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add));
}
like image 41
TalentTuner Avatar answered Nov 05 '22 23:11

TalentTuner