Search code examples
c#.netcollectionssortedlist

C# Sortable collection which allows duplicate keys


I am writing a program to set a sequence in which various objects will appear in report. The sequence is the Y position (cell) on Excel spreadsheet.

A demo part of code is below. What I want to accomplish is to have a collection, which will allow me to add multiple objects and I can get a sorted collection based on the sequence

SortedList list = new SortedList();

Header h = new Header();
h.XPos = 1;
h.name = "Header_1";
list.Add(h.XPos, h);

h = new Header();
h.XPos = 1;
h.name = "Header_2";
list.Add(h.XPos, h);

I know that the SortedList will not allow this and I have been searching for alternate. I don't want to eliminate the duplicates and already tried List<KeyValuePair<int, object>>.

Thanks.


Solution

  • Thanks a lot for your help. While searching more, I found this solution. (Available in Stackoverflow.com in other question)

    First, I created a class which would encapsulate my objects for classes (Headers,Footer etc)

    public class MyPosition
    {
        public int Position { get; set; }
        public object MyObjects{ get; set; }
    }
    

    So this class is supposed to hold on the objects, and PosX of each object goes as int Position

    List<MyPosition> Sequence= new List<MyPosition>();
    Sequence.Add(new MyPosition() { Position = 1, Headerobject });
    Sequence.Add(new MyPosition() { Position = 2, Headerobject1 });
    Sequence.Add(new MyPosition() { Position = 1, Footer });
    
    League.Sort((PosA, PosB) => PosA.Position.CompareTo(PosB.Position));
    

    What eventually I get is the sorted "Sequence" list.