Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this the best way to convert List<T> from models to ObservableCollection<T> in views?

In MVVM development I am constantly converting List<T> from my models to ObservableCollection<T> for my views.

I looked around in .NET for a way to succinctly do this e.g. such as .ToList<> or .ToArray<> or .ToDictionary<> but couldn't find anything similar for ObservableCollection.

Therefore I made the following extention method ConvertToObservableCollection<T>().

Is there a better way to convert List<T> to ObservableCollection<T>, or does every MVVM developer end up writing this extension method at some point?

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;
        }
    }

}
like image 850
Edward Tanguay Avatar asked Dec 12 '22 23:12

Edward Tanguay


2 Answers

Why don't you use the appropriate constructor of ObservableCollection?

ObservableCollection<Customer> ocCustomers = 
         new ObservableCollection<Customer>(customers);
like image 197
bruno conde Avatar answered Dec 15 '22 13:12

bruno conde


Declaring a variable with ObservableCollection constructor works in Silverlight 4 too.

like image 24
Michael Av Avatar answered Dec 15 '22 14:12

Michael Av