C# 性能:使用构造函数或循环使用现有项构造新集合?

C# performance: construct new collection with existing items using constructor or loop?

我搜索了但没有找到答案,可能是因为这个问题不好描述。 例如在 WPF 中,我有一个模型 Test 和一个 List<Test> lst,然后必须构造一个 ObservableCollection<TestViewModel> ObsTests。可能有两种方式:

  1. var ObsTests = new ObservableCollection<TestViewModel>(lst
        .Select(t = > new TestViewModel(t));
    
  2. var ObsTests = new ObservableCollection<TestViewModel>();
    foreach(var test in lst)
    {
        ObsTests.Add(new TestViewModel(test));
    }
    

请告诉我哪个性能更好,如果AsParallel可用,请告诉我最佳解决方案(例如ObservableCollection threadsafe?我正在使用.净 4.5)

没有区别。 Ctor 使用基础 class Collection 中的 Add 方法: 推荐人:click!

public ObservableCollection(List<T> list)
    : base((list != null) ? new List<T>(list.Count) : list)
{
    CopyFrom(list);
}

private void CopyFrom(IEnumerable<T> collection)
{
    IList<T> items = Items;
    if (collection != null && items != null)
    {
        using (IEnumerator<T> enumerator = collection.GetEnumerator())
        {
            while (enumerator.MoveNext())
            {
                items.Add(enumerator.Current);
            }
        }
    }
}

ObservableCollection 基于 Collection 所以它不是线程安全的。 对于线程安全的集合——使用 Concurrent 命名空间中的一些 class。更多关于 MSDN.

您还可以实现自己的超快可观察集合。像这儿: Click!

如果您有某些操作的标准实现,并且可以使用您的代码执行相同的操作,则最好选择标准实现。而且它看起来更小:)