I am having a Observable Collection which contains my data values. I want to use Orderby in that collection but i am getting some exception like
"Cannot convert IEnumurable to ObservableCollection". Is there possible for using OrderBy or give me some options to Sort the Collection ?
Anyone please tell me the solution of this.
Thanks in advance.
My Code is:
get {
return _availableStocks == null ? null : _availableStocks .OrderBy(z => z.Casepack.CasePackContents);
// Here _availableStocks is my collection
//Here i am not able to use orderby in this collection Its showing error line
// Here i need to sort the _availableStocks
}
My Actual code is:
foreach (var cachedStock in AvailableSelectedStocks)
{
if (SelectedStock != null)
{
AvailableStocks= CollectionViewSource.GetDefaultView(_availableStocks);
AvailableStocks.SortDescriptions.Add(new SortDescription(SelectedStock.Casepack.CasePackContents.Count.ToString(), ListSortDirection.Ascending));
//In this above line i am getting the Sort descriptions only i am not getting the datas in the SourceCollection . how can i get values in this Collection
this.SelectedStocks.Remove(SelectedStock);
this.RaisePropertyChanged(Member.Of(() => AvailableStocks));
}
}
The .OrderBy extension returns an IEnumerable, which is causing your problem. Attempting to sort in the getter is also somewhat bad.
I would look into wrapping your observable collection with ICollectionView
I.e
Constructor
Where ‘Name’ is the name of the Property of the class Stock that you wish to sort by.
When you add to the observable collection ‘stocks’, the ‘Stocks’ ICollectionView will be updated and your view will display the items in the sorted order.