Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to efficiently select a range in an observable collection into another observable collection

Something like (pseudo code)

ObservableCollection<TheClass> ob1 = new ObservableCollection<TheClass>();
ob1.Add(...);
ob1.Add(...); 
ob1.Add(...);
ob1.Add(...); 
ObservableCollection<TheClass> ob2;
ob2 = ob1.Range(0, 2);

Keeping into account that both collections can contains a large amount of data.

thanks

like image 548
Patrick Avatar asked Jan 06 '23 21:01

Patrick


1 Answers

ObservableCollection<TheClass> ob1 = new ObservableCollection<TheClass>();
ob1.Add(...);
ob1.Add(...); 
ob1.Add(...);
ob1.Add(...); 
ObservableCollection<TheClass> ob2;

// ob2 = ob1.Range(0, 2);
ob2 = new ObservableCollection(ob1.Skip(0).Take(2));

Now if you really insist on that .Range method, you could write an extension yourself:

public static class ObservableCollectionExtensions
{
    public static ObservableCollection<T> Range(this ObservableCollection<T> sequence, int start, int count)
    {
         return new ObservableCollection(sequence.Skip(start).Take(count));
    }
}

Now your code should compile:

ObservableCollection<TheClass> ob1 = new ObservableCollection<TheClass>();
ob1.Add(...);
ob1.Add(...); 
ob1.Add(...);
ob1.Add(...); 
ObservableCollection<TheClass> ob2;

ob2 = ob1.Range(0, 2);
like image 135
nvoigt Avatar answered Jan 10 '23 11:01

nvoigt