Hello,
To sort a collection view, you can use LINQ (Language-Integrated Query).
Here is an example: Suppose we have a collection called products
which contains the following attributes: Name
(product name), Price
(product price) and Category
(product category).
public class Product { public string Name { get; set; }
public decimal Price { get; set; }
public string Category { get; set; } }
Now, we want to sort products
based on price Products in the collection are sorted in ascending order.
We can use LINQ's OrderBy
method to achieve this requirement:
using System.Linq;
var sortedProducts = products.OrderBy(p => p.Price);
If you want To sort in descending order, simply replace the OrderBy
method with OrderByDescending
:
csharp var sortedProductsInDescendingOrder = products.OrderByDescending(p => p.Price);
If you want to sort based on multiple properties, Multiple parameters can be used in the OrderBy
or OrderByDescending
method.
For example, if you want to sort first by price in ascending order, and then by category in descending order if the price is the same, you can do this:
var sortedProducts = products.OrderBy(p => p.Price).ThenByDescending(p => p.Category);
After sorting, you want to update your Collectionview, you can need to call ToList()
in the end. Then clear the ObservableCollection
and add new items in the Collectionview.
public ObservableCollection<Product> Products{ get; set; }=new ObservableCollection<Product>();
...
var order= Products.OrderByDescending(p => p.Price).ToList();
Products.Clear();
foreach (var item in order)
{
Products.Add(item);
}
Best Regards, Leon Lu
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment". Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.