Home > Software design >  Improve Linq query when sorting UWP DataGrid
Improve Linq query when sorting UWP DataGrid

Time:11-09

I implemented sorting in a UWP DataGrid following the example at How to: Group, sort and filter data in the DataGrid Control

The column sorting event uses a Tag from the data column header to run the specific Linq query, e.g., Tag=“Country”.

My hypothetical datagrid has 3 fields “Country”, “Name”, “Height”, so in order to add sorting to all 3 fields, I would need to duplicate the logic and query for each field with only the “orderby field” being different. Is there a better solution?

if (e.Column.Tag.ToString() == "Country") 
{
  mydg.ItemsSource = new ObservableCollection<Mountain>(
  from item in myData
  orderby item.Country ascending 
  select item);
 }

CodePudding user response:

Take a look at Dynamic LINQ OrderBy on IEnumerable<T> / IQueryable<T>.

You can build up the basic IQueryable<>, dynamically apply a sort based on user selected sort preferences, and then pass the resulting query on as the ItemSource.

  • Related