就我而言,这个 Lambda OrderBy 似乎是多余的 - 是吗



我不想有任何不必要的代码,但我也想"安全"。实证观察表明,下面的 OrderBy 没有任何作用 - 列表已经正确排序。在这种情况下,我可以依靠这种情况并删除该 OrderBy 行吗?

HashSet<int> hashSet = new HashSet<int>();
List<int> listInts = new List<int>();
using (var file = new System.IO.StreamReader(selectedFile)) {
    string line;
    int lineNum = 0;
    int Offset = (int)numericUpDownLinesOfContext.Value;
    while ((line = file.ReadLine()) != null)     {
        lineNum++;
        if (line.Contains(PlatypusToSearchFor)) {
            // This adds the lines before and after that will provide the desired context
            // (N lines from the log file before and after the searched for value)
            hashSet.UnionWith(Enumerable.Range(lineNum - Offset, Offset * 2 + 1));
        }
    }
    // Remove any negative numbers, as well as 0, that might have been added 
    // (0, -1, -2, or -3 are all possibilities, but the first line is #1)
    listInts = hashSet.Where(i => i >= 1).ToList();
    // They seem to be ordered correctly already, but this is just in case:
    listInts = listInts.OrderBy(i => i).ToList();
}

不,您不应该删除OrderByHashSet不保证任何特定的订购。 你可能会在测试中很幸运,但你不能保证它会按照你期望的方式排序。

从 MSDN 文档有关 HashSet (http://msdn.microsoft.com/en-us/library/bb359438.aspx):

集合是不包含重复元素的集合,其 元素没有特定的顺序

(着重号后加)

如前所述HashSet没有任何特定的顺序。如果需要该行为,则可以改用SortedSet,然后不需要OrderBy

UnionWith操作不会保留排序。 但是,您也不必使用 OrderBy 行,因为 .NET 提供了一个公开集合操作和自动排序行为的SortedSet<T>类。

最新更新