5

I am adding some unique french words to a sorted list, but it doesn't seem to differentiate certain words like "bœuf" & boeuf".

private static void TestSortedList()
{

    Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("fr-fr");
    SortedList sortedList = new SortedList(new Comparer(CultureInfo.CurrentCulture));

    try
    {
        sortedList.Add("bœuf", "Value1");
        sortedList.Add("boeuf", "Value1");
    }
    catch(Exception ex)
    {
        Console.WriteLine(ex.ToString());
    }
}

So the following code above throws exception "System.ArgumentException: Item has already been added." Please help!

George Brighton
  • 5,131
  • 9
  • 27
  • 36
  • 1
    But isn't that what it's supposed to do? When sorting in French those two words are considered the same. – RenniePet Dec 23 '13 at 15:27
  • Hi George - is there a way to make .NET consider them not same while sorting? I need to build a list & these 2 words must appear in the final list. – user3129957 Dec 23 '13 at 15:34
  • See the answer below on how you can make it do that, this question explains why. http://stackoverflow.com/questions/492799/difference-between-invariantculture-and-ordinal-string-comparision – Paul Coghill Dec 23 '13 at 15:36

1 Answers1

2
    SortedList sortedList = new SortedList(StringComparer.Ordinal);

    try
    {
        sortedList.Add("bœuf", "Value1");
        sortedList.Add("boeuf", "Value1");
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.ToString());
    }

works. To explain, the Ordinal and OrdinalIgnoreCase comparers compare the characters bytes and they are different for different chars. See Difference between InvariantCulture and Ordinal string comparison too.

Community
  • 1
  • 1
Zebi
  • 8,682
  • 1
  • 36
  • 42
  • 1
    This works, of course, but it's difficult to know if this is acceptable for the OP. By not using French sorting the ordering of the SortedList will be different, for example if the first characters of some words are accented. – RenniePet Dec 23 '13 at 15:36
  • That's right, I edited my post to explain the `Ordinal` comparer so he can think about if it fits or not. – Zebi Dec 23 '13 at 15:38