Thursday, March 07, 2013

SortedSet with duplicate key.

Found a not so expected behavior of SortedSet today.

I did a custom class as such:

        public class MyClass : IComparable
        {
            public string Title { get; set; }
            public string FileName { get; set; }

            public int CompareTo(MyClass other)
            {
                int intTitleCompare = String.CompareOrdinal(this.Title, other.Title);
                return intTitleCompare;
            }

        }

The initial implementation is to use a SortedList/Dictionary and use the Title as key, but it will failed due to my data set having the same Title for multiple files. Thus with the above code, I'm expecting to be able to use SortedSet to have a sorted list of MyClass object while having the "key" being duplicates in the list.

So that did this:
var listOfFiles = new SortedSet();
                listOfFiles.Add(new MyClass()
                    {
                        Title = "cs",
                        FileName = "1.xml"
                    });



                listOfFiles.Add(new MyClass()
                    {
                        Title = "cs",
                        FileName = "2.xml"
                    });

The listOfFiles return me count of 1 instead of 2! This is because the CompareTo function returns 0, and SortedSet will ignore the entry during add.

1 comment:

aparna john said...

Hi,concentrate your efforts on the creating useful and unique contents in Web Design Cochin backed by whole hearted promotion using ethical means to gain higher search engine ranking and large volume of relavent visitors.Thanks..........