简体   繁体   English

如何从为创建数组而编写的 LINQ 创建一个可观察的集合?

[英]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我需要的是创建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.我想要做的是将它作为ListOfModes ObservableCollection 而不是数组。

Is there a way that I can do this without just listing out each element of the array and doing multiple adds?有没有一种方法可以做到这一点,而无需列出数组的每个元素并进行多次添加?

ObservableCollection<T> provides the constructor ObservableCollection<T>(IEnumerable<T>) which allows to initialize a new collection based on an existing enumerable. ObservableCollection<T>提供了构造函数ObservableCollection<T>(IEnumerable<T>) ,它允许基于现有的枚举来初始化一个新的集合。

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.直接从您的 LINQ 语句初始化集合。

In spite of that: Are you really sure, an ObservableCollection is required here?尽管如此:你真的确定,这里需要 ObservableCollection 吗? Since the enumeration values will not change there are no needs of notifications and a simple list or an array would be totally enough.由于枚举值不会改变,因此不需要通知,简单的列表或数组就足够了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM