简体   繁体   English

使ObservableCollection与Linq表达式的结果一起使用

[英]To make a ObservableCollection working with the results of an Linq expression

How to make a ObservableCollection working with the results of an Linq expression? 如何使ObservableCollection与Linq表达式的结果一起使用?

Ex: 例如:

items = new ObservableCollection<Item>(ctx.Items.Local.OrderBy(i => i.Name));
items.Add(new Item { Name = "ITEM NAME" });

At the time of saving the context, the above code does not work because: 保存上下文时,以上代码不起作用,原因是:

var a items.Count; //a is 1
var b ctx.Items.Local.Count; //b is 0 --> Nothing added!!

Why A not equals B?? 为什么A不等于B? Can anyone help? 有人可以帮忙吗?

Obs. 观察 ctx is a DBContext ctx是一个DBContext

I'm not sure what you are hoping to happen. 我不确定您希望发生什么。 a being 1 and b being 0 is what I would expect from the code you have shared. 我希望从您共享的代码中得到a为1而b为0。

Check ObservableCollection's source code in http://referencesource.microsoft.com/#System/compmod/system/collections/objectmodel/observablecollection.cs http://referencesource.microsoft.com/#System/compmod/system/collections/objectmodel/observablecollection.cs中检查ObservableCollection的源代码

The constructor you are using will copy the contents of the list, so any further changes in items will not be reflected in the list used in its constructor, or in this case the IEnumerable. 您使用的构造函数将复制列表的内容,因此项目的任何进一步更改都不会反映在其构造函数或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);
            }
        }
    }
}

If you want to listen to items changes, and reflect the changes in the base list, perhaps you can do this in items.CollectionChanged 如果您想听项目更改,并在基本列表中反映更改,也许可以在items.CollectionChanged

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM