这个Lambda OrderBy在我的案例中似乎是多余的 - 是吗?

B. *_*non 0 c# generics lambda arraylist

我不想要任何不必要的代码,但我也希望"安全".经验观察表明,下面的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();
}
Run Code Online (Sandbox Code Playgroud)

Eth*_*own 5

不,你不应该删除OrderBy. HashSet不保证任何特定的订购.您可能会在测试中获得幸运,但您不能保证它会以您期望的方式订购.

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

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

(重点补充)