Tuesday, January 12, 2010

Sorting a List with a specific String Comparer like Ordinal

Sorting strings is always a tricky issue and a cause of subtle bugs that are hard to unearth until a customer encounters a weird corner case. The AWS SDK for .NET had a bug that resulted in S3 metadata being incorrectly sorted because the SDK used the default String Comparison algorithm. The fix was two fold:
1. Change the ArrayList into a List
2. Specify the correct StringComparer - Ordinal in this case.
            List list = new List(headers.Count);
            foreach (string key in headers.AllKeys)
            {
                string lowerKey = key.ToLower();
                if (lowerKey.StartsWith("x-amz-"))
                {
                    list.Add(lowerKey);
                }
            }
            // Using the recommendations from: 
            // http://msdn.microsoft.com/en-us/library/ms973919.aspx
            list.Sort(StringComparer.Ordinal);

No comments:

Post a Comment