【问题标题】:Why does my ordered list not stay ordered? [duplicate]为什么我的有序列表没有保持有序? [复制]
【发布时间】:2020-06-11 22:34:33
【问题描述】:

我有一堂课:

public class PairODocs
{
    public string Whirred;
    public int Doc1Count = 0;
    public double Doc1Prcntg = 0.0;
    public int Doc2Count = 0;
    public double Doc2Prcntg = 0.0;
}

...及其列表:

List<PairODocs> lstPairODocs;

当我尝试通过 Doc1Prcntg 订购时,如下所示:

lstPairODocs.OrderByDescending(a => a.Doc1Prcntg);

...它显然没有这样做。之后使用下面的循环代码将其添加到 PDF 文档(iText 7):

foreach (PairODocs pod in lstPairODocs)
{
    table.AddCell(pod.Whirred);
    table.AddCell(pod.Doc1Count.ToString());
    table.AddCell(pod.Doc1Prcntg.ToString());
    table.AddCell(pod.Doc2Count.ToString());
    table.AddCell(pod.Doc2Prcntg.ToString());
}

...这是生成的数据:

(仍然按字母顺序,而不是按 Doc1Prcntg 降序)。

我也试过这个:

// after the call to lstPairODocs.OrderByDescending():
List<PairODocs> lstPairODocs2 = lstPairODocs;

...还有这个:

List<PairODocs> lstPairODocs2 = new List<PairODocs>(lstPairODocs);

...然后在循环中用 lstPairODocs2 替换 lstPairODocs:

foreach (PairODocs pod in lstPairODocs2)

...但这并没有什么不同。

【问题讨论】:

标签: c# linq itext


【解决方案1】:

Linq order by 不会改变集合,它会返回一个有序的新集合。抓住它:

YourList = YourList.OrderByDescending..

或者遍历它:

foreach(PairODocs p in YourList.OrderByDescending..)

【讨论】:

  • 第二个选项似乎侵入性最小,而且效果很好。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-23
  • 2019-09-30
  • 2018-05-28
  • 2021-05-24
  • 1970-01-01
相关资源
最近更新 更多