这是在视图中将List <T>从模型转换为ObservableCollection <T>的最佳方法吗?

Edw*_*uay 4 c# generics observablecollection mvvm

MVVM开发中,我不断地List<T>从我的模型转换ObservableCollection<T>为我的视图.

环顾四周,在.NET一种方式来简洁地做到这一点如如.ToList<>.ToArray<>.ToDictionary<>却找不到任何类似的ObservableCollection.

因此我做了以下扩展方法ConvertToObservableCollection<T>().

是否有更好的转换List<T>方式ObservableCollection<T>,或者每个MVVM开发人员最终都会在某个时候编写此扩展方法?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Documents;
using System.Collections.ObjectModel;

namespace TestObser228342
{
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();

            List<string> names = new List<string> { "one", "two", "three" };
            ObservableCollection<string> ocNames = 
                names.ConvertToObservableCollection<string>();
            ocNames.ToList().ForEach(n => Console.WriteLine(n));

            List<Customer> customers = new List<Customer>
            {
                new Customer { FirstName = "Jim", LastName = "Smith" },
                new Customer { FirstName = "Jack", LastName = "Adams" },
                new Customer { FirstName = "Collin", LastName = "Rollins" }
            };
            ObservableCollection<Customer> ocCustomers = 
                customers.ConvertToObservableCollection<Customer>();
            ocCustomers.ToList().ForEach(c => Console.WriteLine(c));
        }
    }

    public static class StringHelpers
    {
        public static ObservableCollection<T> ConvertToObservableCollection<T>
            (this List<T> items)
        {
            ObservableCollection<T> oc = new ObservableCollection<T>();
            foreach (var item in items)
            {
                oc.Add(item);
            }
            return oc;
        }
    }

    public class Customer
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }

        public override string ToString()
        {
            return FirstName + " " + LastName;
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

bru*_*nde 12

你为什么不使用适当的构造函数ObservableCollection

ObservableCollection<Customer> ocCustomers = 
         new ObservableCollection<Customer>(customers);
Run Code Online (Sandbox Code Playgroud)