简体   繁体   中英

how to perform sorting operation for a grid view using linq,?

How to perform sorting operation for a grid view .I have done this(below code) but it is throwing following error.

Error:

 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.

code:

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);

You are mixing string-based sorting mechanism (GridView.Sorting event) with Linq (lambda expressions based sorting).

This article: Handle GridView.OnSorting() and create sorting expression dynamically using LINQ does what you want

at last I have done the following

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();

            }



        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM