Linq初體驗——Order By 通過屬性名稱動態排序

來源:互聯網
上載者:User

當前項目要求能對錶格的所有列進行排序。而我對linq掌握程度使我僅僅能寫出下面這樣的代碼:

 

                case SortFields.Price:                    if (rules == SortRules.ESC)                    {                        result = result.OrderBy(s => s.Price);                    }                    else                    {                        result = result.OrderByDescending(s => s.Price);                    }                    break;                case SortFields.BuyDate:                    if (rules == SortRules.ESC)                    {                        result = result.OrderBy(s => s.BuyDate);                    }                    else                    {                        result = result.OrderByDescending(s => s.BuyDate);                    }                    break;

 

這讓我十分鬱悶,寫枚舉,寫switch,,雖然寫法很簡單,但用這樣的寫法對每個欄位進行排序的話,我將面臨嚴重的體力活。

我想到了ADO的SQL字串拼接,此時的排序要求變的很輕鬆。

那麼作為新生事物的linq,ADO能輕鬆做到的事,沒理由做不到。

順著這樣的思路,在Google上一番搜尋。

在下面的文章中看到了希望:

http://www.cnblogs.com/126/archive/2007/09/09/887723.html

借鑒文章中的代碼,幾番嘗試,終於有點眉目,傳個欄位名字串和類型進行排序。。。

最後在下面的文章中直接找到了現成的(Orz):

http://hi.baidu.com/snake1964/blog/item/0b68d42ac1d4c120d52af149.html

照著上文的代碼,簡化了一下

        public static IQueryable<TEntity> OrderBy<TEntity>(this IQueryable<TEntity> source, string propertyStr) where TEntity : class        {            ParameterExpression param = Expression.Parameter(typeof(TEntity), "c");            PropertyInfo property = typeof(TEntity).GetProperty(propertyStr);            Expression propertyAccessExpression = Expression.MakeMemberAccess(param, property);            LambdaExpression le = Expression.Lambda(propertyAccessExpression, param);            Type type = typeof(TEntity);            MethodCallExpression resultExp = Expression.Call(typeof(Queryable), "OrderBy", new Type[] { type, property.PropertyType }, source.Expression, Expression.Quote(le));            return source.Provider.CreateQuery<TEntity>(resultExp);        }

反射+System.Linq.Expressions下的幾個函數動態產生lambda運算式。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.