I program the messenger on c # c mvvm. I have a large collection of user messages. By opening the correspondence window with a certain person, I get a method

private void MoreMessages() { builder.ConcreateDialogCreater(ids); Datas.offset += 200; } 

which of the total mass of messages selects and adds to the builder.ConcreteDialogList collection only messages belonging to a correspondence with a specific user.

For a possibility of a binding, I equated links to the ReadyCollection = builder.ConcreteListDialog; declared inside the vm of this window ; in the constructor of this window.

Datas.offset + = 200; is a static variable; the offset required to load a new batch of messages. It is first 0 and is used in builder.ConcreateDialogCreater (ids); AT

So, I can not understand how to declare ReadyCollection, so that it can add elements both from the beginning and from the end relative to the elements already contained in it.

What is it for? At first I made it so that this collection is filled in this way: the message stack in it already lies and everything, messages are arranged from the oldest at the beginning of the collection to the newest at the end. And, when the user sends a message - it is added to the very end, like the newly arrived messages.

But now I made the "More Messages" button, which calls the MoreMessages () method and increases the offset, and it is logical that these messages need to be added even higher than those that already exist in it. But how to do this, because we do not have negative indexes, and Insert (0) leaves that all the more and more groups of messages need to be shifted. In the current situation, messages are added to the end of the collection, which violates the correspondence sequence.

What is the way out?

    1 answer 1

    List<T> fine for you.

    To add to the end of the list, you can use List<T>.Add(T value) or .AddRange(T[] Values) if you add an array.

    And to add to the beginning of the list, you can use List<T>.Insert(int index, T Value) where index is set to 0. If you add an array at once, use InsertRange similarly indicating that the insert index is equal to 0.

    • Thanks, yes, I use this option now. But is this a crutch? After all, the entire collection moves down when one element is added. Or is it still normal? InsertRange is not used for ObservableCollection, I also need to display it - Kirill_Levchenko
    • Well, maybe a crutch ... But based on the question, you need a bidirectional list. A regular sheet implements the necessary functionality out of the box so to speak. Alternatively, you can use LinkedList <T>. This is exactly the same bidirectional list. But it does not have the ability to insert an array right away, this functionality will have to be implemented independently - Alexey