4

如何在 linq 中对 myScriptCellsCount.MyCellsCharactersCount (列表 int 类型)进行排序

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

5 回答 5

9

您可以使用 OrderBy 或 Sort,但您应该了解两者之间的区别:

如果您进行排序,它会“就地”对列表进行排序,因此在本例中,变量“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)

编辑

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

如果您使用上面的 LINQ 代码(第二个示例),则每次迭代变量“sorted”时都会进行排序。因此,如果您在超过 1 个 foreach 中使用它,您将重复排序。为避免这种情况,请将上面的代码更改为:

var sorted = list.OrderByDescending(x => x).ToList(); // or .ToArray()

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

如果您只打算枚举一次,则可以省略 ToList/ToArray 调用。

于 2010-06-17T14:24:38.260 回答
9
// using Linq
MyCellsCharactersCount.OrderBy(x => x);            // ascending
MyCellsCharactersCount.OrderByDescending(x => x);  // descending

或者

// not using Linq
MyCellsCharactersCount.Sort();                     // ascending
MyCellsCharactersCount.Sort().Reverse();           // descending
于 2010-06-17T14:12:11.827 回答
1

您应该能够在列表中使用 OrderBy 方法。

IEnumerable sortedList = myScriptCellsCount.MyCellsCharactersCount.OrderBy(anInt => anInt);
于 2010-06-17T14:13:55.710 回答
0
var sorted = from i in MyCellsCharacterCount orderby i descending select i;
于 2012-08-08T10:02:15.210 回答
0

看看这个答案。您可以通过获取您的 List 的 typeOf 来用您的对象替换“Process”。

干杯

于 2012-10-16T17:56:00.337 回答