0

IEnumerable<T>收集了大约 30,000 条在应用程序加载时创建的记录,这些记录ObservableCollection<T>通过执行转换为(这需要大量加载 WPF 应用程序):

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

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

4

2 回答 2

2

唯一IEnumerable允许访问其内容的方法是逐个枚举它们。如果您IEnumerable可以使用List它,它可能能够获取内部数组,但我希望您最终不得不复制所有内容。

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

于 2013-05-23T13:22:53.973 回答
0

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

你是如何“创造”一个?

IEnumerable<T>

Can not new an IEnumerable
此语法失败

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

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

请参阅下面的代码。
在 16 毫秒内从 IEnumerable ctor 创建了一个 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; }
} 
于 2013-05-23T17:09:46.660 回答