詳細(xì)闡述linq動(dòng)態(tài)排序
作者:佚名 
  linq動(dòng)態(tài)排序不是很好實(shí)現(xiàn)的,很多開發(fā)者都被困在了這個(gè)方面,所以筆者今天分享一下自己的經(jīng)驗(yàn),希望能給大家?guī)韼椭?/div>  
 
                       
  linq動(dòng)態(tài)排序不是很好實(shí)現(xiàn)的,很多開發(fā)者都在這個(gè)方面有疑惑,所以筆者今天分享一下自己的經(jīng)驗(yàn),希望能給大家?guī)韼椭?/P>
想實(shí)現(xiàn)linq動(dòng)態(tài)排序就是linq的order by 后跟動(dòng)態(tài)的函數(shù)可以用委托實(shí)現(xiàn),但是發(fā)現(xiàn)實(shí)現(xiàn)委托函數(shù)時(shí)候:
- int testSelector(post p)
 - {
 - ret urn p.Uu;
 - }
 
這個(gè)返回類型受到了限制僅是相同類型的字段可以動(dòng)態(tài)排序是不是Func
- public IEnumerable
 Sort string userName, Func( - selector)
 - {
 - return from post in posts
 - where post.UserName == userName
 - orderby selector(post) descending
 - select post;
 - }
 
這個(gè)函數(shù)的TKey限制只能是一種類型 ?有什么好的實(shí)現(xiàn)嗎?
linq動(dòng)態(tài)排序具體解決的代碼
- public class OrderBy
 - {
 - List
 posts = new List(); - public List
 GtePost() - {
 - for (int i = 0, j=1000; i < 1000 ; i++, j--)
 - {
 - post p = new post();
 - p.Ty = i;
 - p.Uu=j;
 - p.UserName = "1";
 - posts.Add(p);
 - }
 - return posts;
 - }
 - /**////
 - /// Func
 委托的實(shí)現(xiàn) - ///
 - ///
 - ///
 可以動(dòng)態(tài)設(shè)置排序的列 - int testSelector(post p)
 - {
 - return p.Uu;
 - }
 - public IEnumerable
 GetData() - {
 - GtePost();
 - return Sort<int>("", testSelector);
 - }
 - public IEnumerable
 Sort string userName, Func( - TKey> selector)
 - {
 - return from post in posts
 - where post.UserName == userName
 - orderby selector(post) descending
 - select post;
 - }
 - }
 
linq動(dòng)態(tài)排序Code
- void BindData()
 - {
 - OrderBy o = new OrderBy();
 - post p=new post ();
 - this.dataGridView1.DataSource = o.GetData().ToList
 (); - }
 
以上就是對(duì)linq動(dòng)態(tài)排序解決方法的簡單介紹。
【編輯推薦】
責(zé)任編輯:阡陌 
                    來源:
                    博客園
  
 
相關(guān)推薦
 
 
 
 














 
 
 