如何使用Linq对通用列表进行排序?

Pen*_*uen 4 c# linq sorting generic-list .net-3.5

如何在linq中对myScriptCellsCount.MyCellsCharactersCount(list int type)进行排序

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

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

    }
Run Code Online (Sandbox Code Playgroud)
   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);
        }
Run Code Online (Sandbox Code Playgroud)

Axe*_*ger 9

// using Linq
MyCellsCharactersCount.OrderBy(x => x);            // ascending
MyCellsCharactersCount.OrderByDescending(x => x);  // descending
Run Code Online (Sandbox Code Playgroud)

要么

// not using Linq
MyCellsCharactersCount.Sort();                     // ascending
MyCellsCharactersCount.Sort().Reverse();           // descending
Run Code Online (Sandbox Code Playgroud)


JMa*_*sch 8

您可以使用OrderBy或Sort,但您应该了解的2之间存在差异:

如果您进行排序,它会对您的列表进行"就地"排序,因此在此示例中,变量"list"将被排序:


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

如果您执行OrderBy,原始列表不受影响,但会返回一个新的已排序的可枚举:

var sorted = list.OrderByDescending(x => x)
Run Code Online (Sandbox Code Playgroud)

编辑

这个答案最近被推翻了,所以我回顾了它.在我最初的回答中,我遗漏了一个非常重要的细节:

如果使用上面的LINQ代码(第二个示例),则每次迭代变量"sorted"时都会发生排序.所以,如果你有超过1个foreach,你将重复排序.为避免这种情况,请将上面的代码更改为:

var sorted = list.OrderByDescending(x => x).ToList(); // or .ToArray()
Run Code Online (Sandbox Code Playgroud)

这将强制枚举器运行,并将结果存储在已排序.

如果您只想枚举一次,则可以省略ToList/ToArray调用.