Is there a way to convert an observable collection to regular collection?

做~自己de王妃 提交于 2019-12-18 05:57:31

问题


I've got a test collection setup as :

ObservableCollection<Person> MyselectedPeople = new ObservableCollection<Person>();

public MainWindow()
    {
       InitializeComponent();
       FillData();
    }

public void FillData()
    {
        Person p1 = new Person();
        p1.NameFirst = "John";
        p1.NameLast = "Doe";
        p1.Address = "123 Main Street";
        p1.City = "Wilmington";
        p1.DOBTimeStamp = DateTime.Parse("04/12/1968").Date;
        p1.EyeColor = "Blue";
        p1.Height = "601";
        p1.HairColor = "BRN";

        MyselectedPeople.Add(p1);
    }

Once I have this collection built I would like to be able to convert the Observable Collection to the type List.

The reason behind this is my main project is receiving a generic list with data I have to convert it to an Observable collection for use in gridview, listboxes etc. Data is selected within the UI and then sent back to the originating assembly for further usage.


回答1:


I think the quickest way to do this is with LINQ.

 List<Person> personList= MySelectedPeople.ToList(); 

Cheers.




回答2:


Try the following

var list = MyselectedPeople.ToList();

Make sure you have System.Linq as one of your using statements.




回答3:


This should do it...

List<Person> myList = MyselectedPeople.ToList<Person>();



回答4:


I just want to point out that aside from the obvious Linq extension method, List has always had an overload that takes an IEnumerable<T>

return new List<Person>(MyselectedPeople);



回答5:


It's odd that your back-end assembly is coded to only accept List<T>. That's very restrictive, and prevents you from doing useful things like passing an array, or an ObservableCollection<T>, or a Collection<T>, or a ReadOnlyCollection<T>, or the Keys or Values properties of a Dictionary<TKey, TValue>, or any of the myriad of other list-like things out there.

If possible, change your back-end assembly to accept an IList<T>. Then you can just pass in your ObservableCollection<T> as-is, without ever needing to copy its contents into a List<T>.



来源:https://stackoverflow.com/questions/3167752/is-there-a-way-to-convert-an-observable-collection-to-regular-collection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!