Search code examples
c#wpfcollectionviewsource

CollectionViewSource with Sort get sorted Items


I have a datagrid which has as source CollectionViewSource with custom sorting and I need to get sorted items collection as can be seen in datagrid. I can get sorted description and sort source collection, but I need this collection many time.

Is there some way how to get sorted collection which enable indexation (item[index])?


Solution

  • The CollectionViewSource's View property returns a sorted ICollectionView. Since that is an IEnumerable, you could use Linq to create a List from it, which can be accessed by index:

    // using System.Linq;
    
    var list = collectionView.View.Cast<object>().ToList();
    var firstItem = list[0];