简体   繁体   中英

What is the proper way to iterate through an IObservableList<T>?

I'm working on a WPF application that utilizes ReactiveUI and DynamicData. Most of our lists are of the type IObservableList and at times we need to subscribe to changes on this list, and at times we need to simply iterate through the list. My concern is around if we're following the correct pattern for iterating through these lists.

Currently, when we need to iterate through a list, we follow the following pattern:

// Assuming we have an IObservableList<SomeObject> named objList with some data in it
foreach (var obj in objList.Items)
{
    // some operation on obj
}

This pattern works fine, but we're concerned that this isn't a "Reactive" way to do this. Any suggestions?

Thank you!

You itterate through a list using a loop. Each of them works.

for is the obvious first candidate.

while works, but is a bit more writing.

foreach works - if you do not start changing the list. A quirk of foreach is that it only works with enumerators under the hood, and enumerators become invalid if the collection is changed.

One particulay thing to consider however is the "ElementAdded" Notification on (re)building the list. Usually they classes lack AddRange functions.

Unless you tell us what you do with SomeClass Instances during itteration and how the class looks, we can not tell you if it is "reactive" programming. But for me it feels like it is just a Buzzword.

Well, I'm not quite familiarized with IObservableList<T> , but I use Deferred Execution when working with IList<T> .

I would recommend to implement this when working with dynamic data, it will let you get the latest values whenever you need them.

check the link for more details.

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