【问题标题】:Enumerating a OrderedEnumerable changes the order?枚举 OrderedEnumerable 会更改顺序?
【发布时间】:2022-12-03 07:04:59
【问题描述】:
// elements is of type ReadOnlyCollection<IWebElement>
var elements = Context.Driver.FindElements(By.XPath(path));
// sortedElements is of type OrderedEnumerable<IWebElement, int> 
var sortedElements = elements.OrderBy(a => a.point.Y); // a.point.Y is a Point object (so ordering by int)

// inspecting sortedElements here produces the correct sorting by a.point.Y

foreach (var row in sortedElements.ToList()) {
   System.Console.WriteLine(row.point.Y); 
   // here, the rows are no longer in sorted order even though sortedElements is sorted?  
   // i.e., row.point.Y's are not being logged with correct sorting
}

我尝试将元素转换为 .ToList() 或 .ToArray()(与 sortedElements 相同)。令我感到困惑的是,为什么 sortedElements 是明确排序的,但是当我枚举它时,枚举是以未排序的顺序发生的。我认为 ToList() 应该保持秩序..有谁知道这里可能发生了什么?

【问题讨论】:

    标签: c# selenium linq


    【解决方案1】:
    // inspecting sortedElements here produces the correct sorting by a.point.Y
    

    如果您检查 IEnumerable 它将运行枚举器并且已经访问集合中提供顺序的元素。我建议根本不要调用 ToList() ,这样你就会在循环请求时对 Enumerable 进行排序。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-27
      • 1970-01-01
      • 2016-01-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多