views:

161

answers:

3

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);
        }
+5  A: 
// using Linq
MyCellsCharactersCount.OrderBy(x => x);            // ascending
MyCellsCharactersCount.OrderByDescending(x => x);  // descending

or

// not using Linq
MyCellsCharactersCount.Sort();                     // ascending
MyCellsCharactersCount.Sort().Reverse();           // descending
Obalix
It should be OrderByDescending.
XIII
+1  A: 

You should be able to use the OrderBy method on your list.

IEnumerable sortedList = myScriptCellsCount.MyCellsCharactersCount.OrderBy(anInt => anInt);
brainimus
+1  A: 

You can use OrderBy or Sort, but there is a difference between the 2 that you should understand:

If you do sort, it sorts your list "in place", so in this example, the variable "list" gets sorted:


// you can manipulate whether you return 1 or -1 to do ascending/descending sorts
list.Sort((x, y) =>
{
   if (x > y) return 1;
   else if (x == y) return 0;
   else return -1;
});

If you do an OrderBy, the original list is unaffected, but a new, sorted enumerable is returned:

var sorted = list.OrderByDescending(x => x)
JMarsch