WPF: Sort listview by using LINQ

Source: Internet
Author: User

Two years ago, I wrote an article: a simple and easy-to-use method for sorting the click columns of the WPF listview. It demonstrates how to sort the listview through the collectionview in WPF, the specific sorting is as follows:

In the. NET 3.5 + environment, if the target data is ilist, the program uses Expression Tree to generate and set the listmsort attribute of the listcollectionview type for sorting.

In the. NET 3.0 + environment, the sortdescriptions attribute of the original collectionview is used for sorting.

 

However, the preceding sorting method is not very flexible. Therefore, this article demonstrates how to use LINQ for sorting in WPF. Of course, developers do not need to manually write the LINQ sorting code. The program creates a type called linqcollectionview, you can use it to define the sorting method, and the program uses LINQ to execute sorting. Of course, linqcollectionview is only used for sorting. It has no inheritance relationship with the icollectionview interface of WPF, and does not support observablecollection <t> currently.

WPF collectionview was born in. net 3.0, while. net 3.5 and later, while the collectionview of winrt in Windows 8 does not have the sortdescriptions and groupdescriptions attributes. Microsoft recommends that developers use LINQ to operate data directly.

 

: Sample programs in this article

 

For example, our data element type is such a simple class:

Public class item

{

Public item (string name, int score)

{

Name = Name;

Score = score;

}

 

Public string name {Get; private set ;}

Public int score {Get; private set ;}

 

Public static item [] getdata ()

{

Return new item []

{

New item ("Liu", 86 ),

New item ("Zhang", 32 ),

New item ("Li", 21 ),

New item ("Wang", 100 ),

New item ("Zhao", 78)

};

}

}

 

Name indicates the name and score indicates the score. The getdata method is used to generate test data.

The sorting rule is defined as follows:

By default, names are sorted incrementally and case-insensitive.

By default, programs are sorted in descending order.

 

In XAML, define the listview:

<Listview name = "listview">

<Listview. itemcontainerstyle>

<Style targettype = "listviewitem">

<Setter property = "horizontalcontentalignment" value = "stretch"/>

</Style>

</Listview. itemcontainerstyle>

<Listview. View>

<Gridview>

<Gridviewcolumn displaymemberbinding = "{binding name}" header = "name"/>

<Gridviewcolumn header = "score">

<Gridviewcolumn. celltemplate>

<Datatemplate>

<Progressbar Height = "20" value = "{binding score, mode = onetime}" minwidth = "100"/>

</Datatemplate>

</Gridviewcolumn. celltemplate>

</Gridviewcolumn>

</Gridview>

</Listview. View>

</Listview>

 

Then add the Execution Code:

VaR collectionview = new linqcollectionview <item> (

Item. getdata (),

New columnsortdata <item> (x, y) => stringcomparer. ordinalignorecase. Compare (X. Name, Y. Name )),

New columnsortdata <item> (I => I. Score, columnsortdirection. Descending ));

 

Linqcollectionview <item>. setlistview (listview, collectionview );

The program is OK.

 

The main program type is linqcollectionview <t>, and T is the data element type. linqcollectionview inherits from viewmodelbase in mvvm light, because it must provide a set change notification. Note that the Set Change Notification here does not refer to the inotifycollectionchanged interface, and the set itself does not change. A new ienumerable will be generated after the LINQ sorting. <t>, therefore, this new property replaces the original set property.

 

The constructor of this type is as follows:

Public linqcollectionview (ienumerable <t> source, Params columnsortdata <t> [] sortdata)

 

Of course, source is the original set. Sortdata is the set data of specific sorting. Let's look at columnsortdata <t>.

 

Columnsortction ction enumeration indicates the direction of sorting:

Public Enum columnsortction ction

{

Ascending,

Descending

}

Ascending indicates increasing, and descending indicates decreasing.

 

In this case, the initialdirection attribute of columnsortdata <t> represents the sorting direction when this sorting item is performed for the first time, that is, when the gridviewcolumnheader of this column is clicked for the first time, it is sorted in ascending or descending order.

The status attribute can be of the null columnsortction ction type. If it is null, it indicates that the current column is not sorted. Of course, it may be that after sorting, the user clicks another column, the column order is disrupted, and the status attribute is null.

 

The last two attributes are two sorting methods (only one can be selected). The keyselector attribute is used to extract an attribute from a collection project through a func <t, Object> delegate, sort this attribute. Similar to the property name in sortdescription in WPF collectionview (of course, keyselector directly returns the property, sortdescription gets the property through reflection, and keyselector has an absolute performance advantage ).

Another sort method is to use the comparison <t> delegate. This delegate is not defined by me. It is in the system namespace, And. NET 2.0 does. This method is similar to the icomparer type in the customsort attribute of listcollectionview, but directly uses a delegate, so that the user no longer needs to execute the icomparer type.

 

Therefore, columnsortdata has two construction methods:

Public columnsortdata (func <t, Object> selector, columnsortction ction direction = columnsortdirection ction. ascending)

Public columnsortdata (comparison <t> comparison, columnsortdirection direction = columnsortdirection ction. ascending)

 

Then let's look at the Code created in the above linqcollectionview. This will add a comment, which is like this:

VaR collectionview = new linqcollectionview <item> (

Item. getdata (),

New columnsortdata <item> (x, y) => stringcomparer. ordinalignorecase. Compare (X. Name, Y. Name )),

// Use comparison <t> to directly return the sorting result

New columnsortdata <item> (I => I. Score, columnsortdirection. Descending ));

// Use keyselector to return the score attribute

 

 

Download the source code of the current version
Download Page
Note: the link is the Microsoft SkyDrive page. When downloading, use a browser to download it directly. Some download tools may not be available for downloading.
Source code environment: Microsoft Visual Studio express 2012 for Windows Desktop
Note: The Source Code does not contain the referenced external class library file: mvvm light

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.