初始化或延迟加载ObservableCollection<通过IEnumerable记录

本文关键字:记录 IEnumerable 通过 延迟加载 ObservableCollection 初始化 | 更新日期: 2023-09-27 18:15:13

我有一个大约30,000条记录的IEnumerable<T>集合,这些记录是在应用程序加载时创建的,这些记录通过以下方式转换为ObservableCollection<T>(这需要大量的WPF应用程序加载):

IEnumerable<Person> enumerablePeople; //Initialized and contains around 30,000 records
ObservableCollection<Person> people = new ObservableCollection<Person>(enumerablePeople);

是否有一些不同的优化或快速的方法/方式,而不是更新我可以使用,或者如果可能的话,我可以使用某种延迟加载来初始化它,将IEnumerable<Person>转换为ObservableCollection<Person>,以便它加载集合/应用程序更快。

初始化或延迟加载ObservableCollection<通过IEnumerable<T>记录

IEnumerable允许访问其内容的唯一方法是逐个枚举它们。如果您的IEnumerable作为List可用,那么可能能够抓取内部数组,尽管我预计您最终将不得不复制所有内容。

30000引用不应该花很长时间来复制。如果它花费的时间超过一两秒钟,我会确保它没有调用一些缓慢的事件处理程序或为每个添加的项目更新UI。

人们试图帮助你,而你却不听。

你是如何"创造"一个?

IEnumerable<T>

不能新建IEnumerable
这个语法失败

IEnumerable<Person> IPeople = new IEnumerable<Person>(); 

您可能正在应用程序加载中创建对IEnumerable的引用。
但是你不是在创建一个IEnumerable对象,因为根本就没有这样的东西。
IEnumerable是一个接口而不是一个集合——它不能被更新。

参见下面的代码。在16毫秒内从IEnumerable对象中创建100,000个ObservableCollection

System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
sw.Start();
System.Diagnostics.Debug.WriteLine(iPeople.Count().ToString());
System.Diagnostics.Debug.WriteLine(sw.ElapsedMilliseconds.ToString());  // 13 ms
sw.Restart();
ObservableCollection<Person> ocPeople = new ObservableCollection<Person>(iPeople);         
System.Diagnostics.Debug.WriteLine(sw.ElapsedMilliseconds.ToString());  // 16 ms
sw.Restart();
System.Diagnostics.Debug.WriteLine(iPeople.Count().ToString());
System.Diagnostics.Debug.WriteLine(sw.ElapsedMilliseconds.ToString());  //  8 ms
sw.Restart();
System.Diagnostics.Debug.WriteLine(ocPeople.Count().ToString());
System.Diagnostics.Debug.WriteLine(sw.ElapsedMilliseconds.ToString());  //  1 ms
sw.Restart();
List<Person> lPeople = new List<Person>(iPeople);
System.Diagnostics.Debug.WriteLine(sw.ElapsedMilliseconds.ToString());  // 10 ms
sw.Restart();
ObservableCollection<Person> ocPeople2new = new ObservableCollection<Person>(lPeople);
System.Diagnostics.Debug.WriteLine(sw.ElapsedMilliseconds.ToString());  //  6 ms
public IEnumerable<Person> iPeople
{
    get
    {
        for (int i = 0; i < 100000; i++) yield return new Person(i);
    }
}
public class Person
{
    public Int32 ID { get; private set; }
    public Person(Int32 id) { ID = id; }
}