Skip to content

Incorrect behavior of SortedDictionary when used with OrdinalIgnoreCase comparer #29112

@AndreyChechel

Description

@AndreyChechel

Number of entries added to a SortedDictionary shouldn't be affected by the order of insertion.
The issue is reproducible in non-Windows environments (checked in .NET Core 2.1 / 2.2).
See playground.

There are 5 entries being inserted in the sample below. The dictionary is supposed to have 4 entries, since two records have the equal keys in terms of OrdinalIgnoreCase comparer,

  • ["narınnarın"] = 3
  • ["narinnarin"] = 4

Proving snippet:

var equal = string.Equals("narınnarın", "narinnarin", StringComparison.OrdinalIgnoreCase);
Console.WriteLine(equal); // "True" (on Linux/Mac)

Sample

using System;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.Versioning;

public class Program
{
  public static void Main()
  {
    Console.WriteLine(Environment.OSVersion);

    // ------------------------------------------------------------------------------
    // Test Case 1
    // Expected output: 4
    // Actual output: 4
    // ------------------------------------------------------------------------------

    var dict1 = new SortedDictionary<string, int>(StringComparer.OrdinalIgnoreCase);

    dict1["naryn"] = 1;
    dict1["нарын"] = 2;
    dict1["narınnarın"] = 3;
    dict1["narinnarin"] = 4;
    dict1["ナルインナルイン"] = 5;

    Console.WriteLine(dict1.Count); // Outputs 4 - OK

    // ------------------------------------------------------------------------------
    // Test Case 2 (changed order of insertion)
    // Expected output: 4
    // Actual output: 5
    // ------------------------------------------------------------------------------

    var dict2 = new SortedDictionary<string, int>(StringComparer.OrdinalIgnoreCase);

    dict2["naryn"] = 1;
    dict2["нарын"] = 2;
    dict2["ナルインナルイン"] = 3;
    dict2["narınnarın"] = 4;
    dict2["narinnarin"] = 5;

    Console.WriteLine(dict2.Count); // Outputs 5 (Expected 4)
  }
}

Actual Output

Unix 5.0.3.200
4
5

Expected Output

Unix 5.0.3.200
4
4

Metadata

Metadata

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions