How can i sort Generic list with Linq?

Penguen picture Penguen · Jun 17, 2010 · Viewed 12.6k times · Source

How can i sort myScriptCellsCount.MyCellsCharactersCount (list int type) in linq

    public class MyExcelSheetsCells
    {
        public List<int> MyCellsCharactersCount { get; set; }

        public MyExcelSheetsCells()
        {
            MyCellsCharactersCount = new List<int>();
        }

    }
   void ArrangedDataList(DataTable dTable)
        {
            DAL.MyExcelSheets myexcelSheet = new DAL.MyExcelSheets();
            myScriptCellsCount = new TestExceltoSql.DAL.MyExcelSheetsCells();

            foreach (DataColumn col in dTable.Columns)
                myexcelSheet.MyColumnNames.Add(col.ColumnName.ToString());
            foreach(DataColumn dc in dTable.Columns)
            foreach (DataRow  dr in dTable.Rows)
                myScriptCellsCount.MyCellsCharactersCount.Add(dr[dc].ToString().Length);
          //How can i sort desc
            //myScriptCellsCount.MyCellsCharactersCount = from list in myScriptCellsCount.MyCellsCharactersCount
            //                                            orderby list.CompareTo( descending
            //                                            select list;
            CreatSqlTable(myexcelSheet.MyColumnNames, dTable.TableName, myScriptCellsCount.MyCellsCharactersCount[0].ToString());
            myscript.WriteScript(myscript.SqlScripts);
        }

Answer

AxelEckenberger picture AxelEckenberger · Jun 17, 2010
// using Linq
MyCellsCharactersCount.OrderBy(x => x);            // ascending
MyCellsCharactersCount.OrderByDescending(x => x);  // descending

or

// not using Linq
MyCellsCharactersCount.Sort();                     // ascending
MyCellsCharactersCount.Sort().Reverse();           // descending