简体   繁体   English

有没有办法从ObservableCollection获得范围?

[英]Is there a way to get a range from an ObservableCollection?

I would like to get a range from an ObservableCollection for the purpose of looping through it and changing a property on those items. 我想从ObservableCollection中获取一个范围,以便循环遍历它并更改这些项的属性。 Is there an easy built-in way to do this with the ObservableCollection class? 使用ObservableCollection类有一个简单的内置方法吗?

You can use Skip and Take . 你可以使用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> . 对于循环, ObservableCollection<T>派生自Collection<T> ,并实现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. 如果你想通过LINQ对集合进行查询,你有几个选择。 You can use Skip() and Take() , or build a new range and access by index: 您可以使用Skip()Take() ,或者通过索引构建新范围和访问:

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): ObservableCollection<T>实现了Colletion<T> ,它实现了IEnumerable所以你应该能够做到(如果你正在寻找一个匹配给定条件的范围):

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): 或任意范围(在这种情况下,它需要项目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. Skip and Take是用于分页集合的linq扩展方法。

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

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