简体   繁体   中英

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?

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?? Can anyone help?

Obs. ctx is a 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.

Check ObservableCollection's source code in http://referencesource.microsoft.com/#System/compmod/system/collections/objectmodel/observablecollection.cs

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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