使 ObservableCollection 使用 Linq 表达式的结果
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 是我对您共享的代码的期望。
中 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
中做到这一点
如何使 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 是我对您共享的代码的期望。
中 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