有没有办法将可观察集合转换为常规集合?
我有一个测试集合设置为:
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);
}
一旦构建了这个集合,我希望能够将可观察集合转换为列表类型。
这背后的原因是我的主要项目正在接收一个包含数据的通用列表,我必须将其转换为可观察集合以在网格视图、列表框等中使用。数据在 UI 中选择,然后发送回原始程序集以供进一步使用。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我认为最快的方法是使用 LINQ。
干杯。
I think the quickest way to do this is with LINQ.
Cheers.
请尝试以下操作
确保您将 System.Linq 作为您的 using 语句之一。
Try the following
Make sure you have
System.Linq
as one of your using statements.这应该可以做到...
This should do it...
我只是想指出,除了明显的 Linq 扩展方法之外,List 始终有一个需要
IEnumerable
的重载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>
奇怪的是,您的后端程序集被编码为仅接受
List
。这是非常严格的,并且阻止您执行有用的操作,例如传递数组、ObservableCollection
、Collection
或ReadOnlyCollection
;T>
,或者Dictionary
的Keys或Values属性,或者任何其他类似列表的东西。如果可能,请更改后端程序集以接受
IList
。然后,您可以按原样传入ObservableCollection
,而无需将其内容复制到List
中。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 anObservableCollection<T>
, or aCollection<T>
, or aReadOnlyCollection<T>
, or the Keys or Values properties of aDictionary<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 yourObservableCollection<T>
as-is, without ever needing to copy its contents into aList<T>
.