如何使用linq对网格视图执行排序操作?

时间:2013-10-19 12:17:44

标签: asp.net winforms linq

如何对网格视图执行排序操作。我已经完成了这个(在代码下面),但确实如此 抛出以下错误。

错误:

 the type arguments for method 'System.Linq.Enumerable.OrderBy<TSource,TKey>(System.Collections.Generic.IEnumerable<TSource>,
     System.Func<TSource,TKey>, System.Collections.Generic.IComparer<TKey>)' 
    cannot be inferred from the usage.

代码:

gridview1.DataSource = (from bk in bookList
                                join ordr in bookOrders
                                on bk.BookID equals ordr.BookID
                                select new
                                {
                                    BookID = bk.BookID,
                                    BookNm = bk.BookNm,
                                    PaymentMode = ordr.PaymentMode
                                }).AsQueryable().OrderBy(e.SortExpression,e.SortDirection);

2 个答案:

答案 0 :(得分:1)

您正在将基于字符串的排序机制(GridView.Sorting事件)与Linq(基于lambda表达式的排序)混合。

这篇文章:Handle GridView.OnSorting() and create sorting expression dynamically using LINQ做你想做的事情

答案 1 :(得分:0)

最后我做了以下

protected void gridview1_Sorting(object sender, GridViewSortEventArgs e)
        {
            int p = int.Parse(Session["p"].ToString());
            p++;
            Session["p"] = p;
            if (p % 2 == 0)
            {
                var A = from bk in bookList
                        join ordr in bookOrders
                        on bk.BookID equals ordr.BookID
                        select new
                        {
                            BookID = bk.BookID,
                            BookNm = bk.BookNm,
                            PaymentMode = ordr.PaymentMode
                        };


                gridview1.DataSource = A.OrderBy(x => x.BookID);
                gridview1.DataBind();

            }
            else
            {
                var A = from bk in bookList
                        join ordr in bookOrders
                        on bk.BookID equals ordr.BookID
                        select new
                        {
                            BookID = bk.BookID,
                            BookNm = bk.BookNm,
                            PaymentMode = ordr.PaymentMode
                        };


                gridview1.DataSource = A.OrderByDescending(x=>x.BookID);
                gridview1.DataBind();

            }



        }