Wednesday, December 7, 2011

Sorting and limiting datetime rows in datatable using linq


  private DataTable SortAndLimitRowsDateWise(DataTable dtTable, int datepositionintable, int returnrowscount)
    {
        DataTable dtReturnTable = new DataTable();
        DataTable dtMergeTable = new DataTable();

        if (returnrowscount <= dtTable.Rows.Count)
        {
            //ordering datewise the fields, it will convert automatically the datefields
            EnumerableRowCollection<DataRow> query = from order in dtTable.AsEnumerable()
                                                     orderby Convert.ToDateTime(order.Field<String>(datepositionintable))
                                                     select order;

            DataView view = query.AsDataView();
            dtMergeTable = view.ToTable();

            //selecting return rows count
            var dtTrec = from item in dtMergeTable.AsEnumerable()
                         select item;
            var topN = dtTrec.Take(returnrowscount);

            dtReturnTable = dtMergeTable.Clone();

            foreach (DataRow drrow in topN.ToArray())
            {

                dtReturnTable.ImportRow(drrow);
            }


        }

        return dtReturnTable;
    }

No comments:

Post a Comment