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);
}
// using Linq
MyCellsCharactersCount.OrderBy(x => x); // ascending
MyCellsCharactersCount.OrderByDescending(x => x); // descending
or
// not using Linq
MyCellsCharactersCount.Sort(); // ascending
MyCellsCharactersCount.Sort().Reverse(); // descending
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)
Edit
This answer was recently upvoted, so I reviewed it. In my original response, I left out a really important detail:
If you use the LINQ code above (second example), the sort is going to occur every time you iterate over the variable "sorted". So, if you have it in more than 1 foreach, you will repeat the sort. To avoid that, change the code above to:
var sorted = list.OrderByDescending(x => x).ToList(); // or .ToArray()
That will force the enumerator to run, and will store the result in sorted.
If you are only going to enumerate it once, you can leave out the ToList/ToArray call.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With