C # Is it possible to abstract an orderby LINQ clause into a function parameter?

I have an ObservableCollection binding on a WPF list view. I am looking to be able to sort the columns of a ListView control by clicking on the column heading. To do this, I sort the ObservableCollection and let the binding take care of updating the GUI.

To sort the ObservableCollection, I use the following code:

sortedData = new ObservableCollection<Tag>( from x in data
                                            orderby x.ID descending
                                            select x );
data = sortedData;

NB: data bound to ListView

The problem I am facing is that for each column there will be a lot of copy-paste code to achieve the desired effect. Is it possible to pass part of orderby x.ID in descending order to the LINQ operator as a function parameter?

Or is there an easier way to achieve the desired result?

+3
6

Func , -.

, .

public ObservableCollection<Tag> Sort(Func<ObservableCollection<Tag>> sortFunc)  
{  
    //do something else  
    data = sortFunc();  
    //do something else  
}

Sort(list.OrderByDescending(x => x.ID));

ObservableCollection.

+3

:

Func<Tag, int> sortFunc = x => -x.ID;

( , .)

IEnumerable<Tag>:

var sortedData = new ObservableCollection<Tag>(data.OrderBy(sortFunc));
+3

, thekip Func , .

sortColumn( "ID", x => x.ID );

protected void sortColumn<T>( string name, Func<Tag, T> selector )
{
    ObservableCollection<Tag> sortedData = new ObservableCollection<Tag>( TagData.OrderBy( selector ) );

    data = sortedData;
}
+1

Dynamic Linq

- :

var sortExpr = "x.ID";

IQueryable<Tag> sortedQuery = query.OrderBy(sortExpr);

0
source

You can use Dynamic Query.It will compile LINQ statements on the fly, dynamically, at runtime.

For instance:

var query =
           db.Customers.Where("City == @0 and Orders.Count >= @1", "London", 10).
           OrderBy("CompanyName").
           Select("New(CompanyName as Name, Phone)");

You can get it here: http://code.msdn.microsoft.com/DynamicQuery-f65f6a4d

0
source

All Articles