Sorting CollectionView using Orderby in C#


We already learned Filtering, lambad experssion on collection view, and the last one you may want to know how to get a sorted list from a collection view.

AsEnumerable () function makes it easier to sort collection view. In our example we had a StockView class which hold information for Stock of an inventory.

StockView

class StockView{
  public string Batch{ get; set; }
        public int Qty{ get; set; }
        public string Product { get; set; }
  public DateTime Expiry{ get; set; }
}

Then we had a ListCollection view which hold information of all baches of available products. All I wan is to sort out the list. Following code serve the need

 IOrderedEnumerable<StockView> sorted = null;
  sorted = collectionView.SourceCollection.Cast<StockView>()
.AsEnumerable().OrderBy(z => z.Expiry);

As from the last article on lambada experession we learned how to use them. Here we use lambda fuction sort the collection by

  • Using the underlying sourceobject of the collection to get original data
  • Then we Casting the cource to StockView, which is our ViewClass
  • Invoking AsEnumerable() function to access OrderBy functionality
  • Finally created lambda expression for sorting the list

What Next ? Try yourself , sorting Inventory by ProductWise and BatchWise

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.