Is there a way to get a range from an ObservableCollection?

I would like to get a range from an ObservableCollection to scroll it and change the property for these elements. Is there a simple built-in way to do this with the ObservableCollection class?

+3
source share
4 answers

You can use Skipand Take.

System.Collections.ObjectModel.ObservableCollection<int> coll = 
    new System.Collections.ObjectModel.ObservableCollection<int>()
        { 1, 2, 3, 4, 5 };
foreach (var i in coll.Skip(2).Take(2))
{
    Console.WriteLine(i);
}
+6
source

For the cycle, ObservableCollection<T>comes from Collection<T>and implements IList<T>. This allows you to loop through the index:

for (int i=5;i<10;++i)
{
     DoSomething(observableCollection[i]);
}

LINQ, . Skip() Take(), :

var range = Enumerable.Range(5, 5);
var results = range.Select(i => DoMappingOperation(observableCollection[i]));

:

var results = observableCollection.Skip(5).Take(5).Select(c => DoMappingOperation(c));
+3

ObservableCollection<T>implements Colletion<T>, which implements IEnumerable, so that you can do this (if you are looking for a range that matches the given criteria):

foreach(var item in observerableCollection.Where(i => i.prop == someVal))
{
    item.PropertyToChange = newValue;
}

Or an arbitrary range (in this case, it takes points 10 - 40):

foreach(var item in observableCollection.Skip(10).Take(30))
{
    item.PropertyToChange = newValue;
}
+1
source
foreach(var item in MyObservableProperty.Skip(10).Take(20))
{
  item.Value = "Second ten";
}

Skip and Take are linq extension methods used for paging the collection.

+1
source

Source: https://habr.com/ru/post/1773259/


All Articles