Janice_Feb_1998
Janice_Feb_1998

Reputation: 23

How can I create an observable collection from LINQ that was written to create an array?

I have this code that creates an Array:

private ParamViewModel[] _mode;
public ParamViewModel[] Mode{ get => _mode; set => SetProperty(ref _mode, value); }

Mode = Enum.GetValues(typeof(MO))
   .Cast<MO>()
   .Select(x => new ParamViewModel { Id = (int)x, Name = x.Text() })
   .ToArray();

What I need is to create ListOfModes

    private ObservableCollection<ParamViewModel> _listOfModes;
    public ObservableCollection<ParamViewModel> ListOfModes{
        get => _listOfModes;
        set => SetProperty(ref _listOfModes, value);
    }

What I'm trying to do is to have this as a ListOfModes ObservableCollection instead of an array.

Is there a way that I can do this without just listing out each element of the array and doing multiple adds?

Upvotes: 0

Views: 105

Answers (1)

Fruchtzwerg
Fruchtzwerg

Reputation: 11389

ObservableCollection<T> provides the constructor ObservableCollection<T>(IEnumerable<T>) which allows to initialize a new collection based on an existing enumerable.

So

ObservableCollection<ParamViewModel> ListOfModes
    = new ObservableCollection<ParamViewModel>(
        Enum.GetValues(typeof(MO))
            .Cast<MO>()
            .Select(x => new ParamViewModel { Id = (int)x, Name = x.Text() }));

initializes the collection directly from your LINQ statement.

In spite of that: Are you really sure, an ObservableCollection is required here? Since the enumeration values will not change there are no needs of notifications and a simple list or an array would be totally enough.

Upvotes: 1

Related Questions