![](/img/trans.png)
[英]Roll up totals of an ObservableCollection<MyType> with a Linq expression
[英]To make a ObservableCollection working with the results of an Linq expression
如何使ObservableCollection與Linq表達式的結果一起使用?
例如:
items = new ObservableCollection<Item>(ctx.Items.Local.OrderBy(i => i.Name));
items.Add(new Item { Name = "ITEM NAME" });
保存上下文時,以上代碼不起作用,原因是:
var a items.Count; //a is 1
var b ctx.Items.Local.Count; //b is 0 --> Nothing added!!
為什么A不等於B? 有人可以幫忙嗎?
觀察 ctx是一個DBContext
我不確定您希望發生什么。 我希望從您共享的代碼中得到a為1而b為0。
在http://referencesource.microsoft.com/#System/compmod/system/collections/objectmodel/observablecollection.cs中檢查ObservableCollection的源代碼
您使用的構造函數將復制列表的內容,因此項目的任何進一步更改都不會反映在其構造函數或IEnumerable中使用的列表中。
public ObservableCollection(IEnumerable<T> collection)
{
if (collection == null)
throw new ArgumentNullException("collection");
CopyFrom(collection);
}
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);
}
}
}
}
如果您想聽項目更改,並在基本列表中反映更改,也許可以在items.CollectionChanged
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.