I would like to get a range from an ObservableCollection for the purpose of loop开发者_运维技巧ing through it and changing a property on those items. Is there an easy built-in way to do this with the ObservableCollection class?
You can use Skip
and 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);
}
For looping, ObservableCollection<T>
derives from Collection<T>
, and implements IList<T>
. This lets you loop by index:
for (int i=5;i<10;++i)
{
DoSomething(observableCollection[i]);
}
If you want to do queries on the collection via LINQ, you have a couple of options. You can use Skip() and Take(), or build a new range and access by index:
var range = Enumerable.Range(5, 5);
var results = range.Select(i => DoMappingOperation(observableCollection[i]));
Or:
var results = observableCollection.Skip(5).Take(5).Select(c => DoMappingOperation(c));
ObservableCollection<T>
implements Colletion<T>
which implements IEnumerable
so you should be able to do (if you're looking for a range that matches a given criteria):
foreach(var item in observerableCollection.Where(i => i.prop == someVal))
{
item.PropertyToChange = newValue;
}
Or an arbitrary range (in this case it takes items 10 - 40):
foreach(var item in observableCollection.Skip(10).Take(30))
{
item.PropertyToChange = newValue;
}
foreach(var item in MyObservableProperty.Skip(10).Take(20))
{
item.Value = "Second ten";
}
Skip and Take are linq extension methods used for paging a collection.
精彩评论